cases: Dispatches from an expression to a matching pattern

Description Usage Arguments Value See Also Examples

View source: R/cases.R

Description

Given an expression of a type defined by the := operator, cases matches it against patterns until it find one that has the same structure as expr. When it does, it evaluates the expression the pattern is associated with. During matching, any symbol that is not quasi-quoted will be considered a variable, and matching values will be bound to such variables and be available when an expression is evaluated.

Usage

1
cases(expr, ...)

Arguments

expr

The value the patterns will be matched against.

...

A list of pattern -> expression statements.

Value

The value of the expression associated with the first matching pattern.

See Also

:=

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
linked_list := NIL | CONS(car, cdr : linked_list)
lst <- CONS(1, CONS(2, CONS(3, NIL)))
len <- function(lst, acc = 0) {
    cases(lst,
          NIL -> acc,
          CONS(car,cdr) -> len(cdr, acc + 1))
}
len(lst)

list_sum <- function(lst, acc = 0) {
    cases(lst,
          NIL -> acc,
          CONS(car,cdr) -> list_sum(cdr, acc + car))
}
list_sum(lst)

pmatch documentation built on Oct. 19, 2018, 5:04 p.m.