match_with: Match With

Description Usage Arguments Details See Also Examples

Description

Function to check a variable using pattern matching.

Usage

1

Arguments

x

The variable to pattern-match

...

Pairs of one pattern (value or list or magrittr sequence) and one result function

Details

match_with(variable, pattern, result-function, ... If variable matches a pattern, result-function is called. For comparing optional types, it is a better habit to use match_with than a conditional statement.

  1. Each pattern can be either:

    • an object or a primitive type (direct comparison with variable),

    • a list (match if variable is in the list),

    • a magrittr functional sequence that matches if it returns variable . The dot . denotes the variable to be matched.

  2. If result-function takes no arguments, it will be called as is. Else, the only argument that will be sent is variable. You can also use the fallthrough function fallthrough() to permit the matching to continue even if the current pattern is matched.

See Also

option(), none

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
library(magrittr)

a <- 5
match_with(a,
  . %>% option(.),     paste,
  none, function()   "Error!"
)
## [1] 5

match_with(a,
  1,                   function()  "Matched exact value",
  list(2, 3, 4),       function(x) paste("Matched in list:", x),
  . %>% if (. > 4) .,  function(x) paste("Matched in condition:", x)
)
## [1] "Matched in condition: 5"

antoinechampion/optional documentation built on May 13, 2019, 3:06 a.m.