Compare - Pattern matching
match_hash.RdPattern matching functions to return a value based on a case of x. Similar
to switch() but allows for any type for object as the case. Cases are two
sided formulas with the LHS being the case and the RHS being the return
value.
For
match_hashandmatch_id, cases are any R object to directly compare withx.For
match_ptype, cases are prototypes to check ifxis_ptype().For
match_when, cases are any predicate expression, that matches when it evaluates toTRUE.
Arguments
- x
[
any] Object to match.- ...
[
<formula>each] Cases to match. Each case is a formula with the left-hand side being the value to match against and the right-hand side being the value to return if the case matches. Cases are evaluated in order, and in the caller environment.- nomatch
[
any] Value to return if no cases match. Usestop()or similar to err.- htab, type, size
[
hashtab()| NULL,character(1)|NULL,integer(1)|NULL] Formatch_hash: an existing hash table, or the arguments passed toutils::hashtab()to create a new one.- fun, args_id
[
character(1),list()] Formatch_id: which 'identical' function to use,"identical"foridentical()or"identical2"foridentical2(); and a list of arguments to pass to it.- args_ptype
[
list()] Formatch_ptype. A list of arguments to pass tois_ptype().
Details
The return value is evaluated dynamically and can refer to x, except for
match_hash, which in turn is faster and can be supplied a pre-built hash
table.
Examples
match_hash(1.42, 1.42 ~ base::sum, "oi" ~ -Inf) #> base::sum
#> function (..., na.rm = FALSE) .Primitive("sum")
# The htab can be reused to speed up repeated calls to match_hash():
htab <- utils::hashtab(size = 2)
utils::sethash(htab, 1.42, base::sum)
utils::sethash(htab, "oi", -Inf)
match_hash(1.42, htab = htab) #> base::sum
#> function (..., na.rm = FALSE) .Primitive("sum")
match_id(1.42, "oi" ~ -Inf, 1.42 ~ .x * 2) #> 2.84
#> [1] 2.84
match_ptype(1.42, character() ~ "chr", double() ~ "dbl") #> "dbl"
#> [1] "dbl"
match_when("oi", grepl("1", .x) ~ "1", grepl("o", .x) ~ "o") #> "o"
#> [1] "o"