Description Usage Arguments Details Examples
Only supports those functionalities. Guard is still under consideration, not yet completely implemented.
Constatnt Pattern (like 1, "1", NULL as R's atomic expression)
Cons Pattern (x::xs)
Tuple Pattern with matching symbols (VECSXP is used instead of Tuple)
Wildcard Pattern (., _, otherwise)
Guard clauses (when using one of getGroupMembers("Compare"), '!', any, all, identical, and isTRUE)
There are three Wildcard Symbol, '.', '_', and ‘otherwise’. You can use one of them in the bottom part of arguments of 'match_with'.
1 |
... |
The first (actual) argument of ... is trying to match following patterns. |
Just like Hakell's "case of" or OCaml's "match with" but not support guard syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | # Syntax
# f <- function(expr) {
# match_with(expr
# , pattern_1 -> res_1
# , pattern_2 -> res_2
# ...
# , pattern_n -> res_n
# )
# }
fib <- function(n) {
match_with(n
, 0 -> 0
, 1 -> 1
, . -> fib(n - 1) + fib(n - 2)
)
}
fib(10)
fizzbuzz <- function(z) {
match_with(list(z %% 3, z %% 5)
, list(0, 0) -> "FizzBuzz"
, list(0, .) -> "Fizz"
, list(., 0) -> "Buzz"
, otherwise -> as.character(z)
)
}
sapply(1:30, fizzbuzz)
# compare with Haskell's definition
# https://wiki.haskell.org/Fold
# Note:
# If lst is R's list (VECSXP), `length(lst) == 0` can be replaced with `list()`.
# If lst is R's integer vector (INTSXP), `length(lst) == 0` can be replaced with `integer(0)`.
# If lst is R's numeric vector (REALSXP), `length(lst) == 0` can be replaced with `numeric(0)`.
## Not run:
foldr <- function(f, init, lst) {
match_with(lst
, length(lst) == 0 -> init
, x::xs -> f(x, foldr(f, init, xs))
)
}
foldl <- function(f, init, lst) {
match_with(lst
, length(lst) == 0 -> init
, x::xs -> foldl(f, f(init, x), xs)
)
}
foldr(function(x, y) paste0("(", x, "+", y, ")"), "0", as.character(1:13))
foldl(function(x, y) paste0("(", x, "+", y, ")"), "0", as.character(1:13))
len <- function(xs) {
match_with(xs
, length(xs) == 0 -> 0
, y::ys -> 1 + len(ys)
)
}
len(c(10, 11, 12))
len(list(10, 11, 12))
## End(Not run)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.