match_with: Patern Matching for R

Description Usage Arguments Details Examples

Description

Only supports those functionalities. Guard is still under consideration, not yet completely implemented.

There are three Wildcard Symbol, '.', '_', and ‘otherwise’. You can use one of them in the bottom part of arguments of 'match_with'.

Usage

1

Arguments

...

The first (actual) argument of ... is trying to match following patterns.

Details

Just like Hakell's "case of" or OCaml's "match with" but not support guard syntax.

Examples

 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)

TobCap/matchwith documentation built on May 9, 2019, 4:51 p.m.