pmatch (version 0.1.4)

cases: Dispatches from an expression to a matching pattern

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

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

Run this code
# NOT RUN {
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)

# }

Run the code above in your browser using DataLab