match_with: Match With

View source: R/optional.R

match_withR Documentation

Match With

Description

Function to check a variable using pattern matching.

Usage

match_with(x, ...)

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

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 6, 2022, 10:59 a.m.