Learn R Programming

pmatch (version 0.1.4)

case_func: Creates a pattern matching function.

Description

Creates a function that can contain expressions of a type defined by the := operator. The first argument of the generated function will be matched against patterns provided in the ... parameter of this function.

Usage

case_func(...)

Arguments

...

A list of variables for the function in addition the data to be matched against which will automatically added plus pattern -> expression statements.

Value

A function that can pattern match

Details

When you call the generated function, and the first argument is matching a pattern, 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.

Functions created with case_func do not support the .. operator, but you can always create constructors for fixed-number tuples, e.g.

tuples := ..(first, second) | ...(first, second, third)

Be careful not to use . here, if you use dot as a generic variable.

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 <- case_func(acc = 0,
   NIL -> acc,
   CONS(car,cdr) -> len(cdr, acc + 1)
)
len(lst)

list_sum <- case_func(acc = 0,
   NIL -> acc,
   CONS(car,cdr) -> list_sum(cdr, acc + car)
)
list_sum(lst)

tuples := ..(first, second) | ...(first, second, third)
f <- case_func(..(.,.) -> 2, ...(.,.,.) -> 3)
f(..(1, 2))
f(...(1, 2, 3))

# }

Run the code above in your browser using DataLab