R/case_func.R
case_trfunc.Rd
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.
case_trfunc(...)
... | A list of variables for the function in addition
the data to be matched against which will automatically added
plus |
---|
A function that can pattern match
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.
This function works like case_func
but implements the "tail-recursion
optimisation", which means that it replaces tail-recursive calls with reassignment
to local variables and looping. Since the scoping rules are different between
recursive calls and loops, you cannot use closures with this transformation
unless you take special care to bind all local values explicitly.
This function cannot know which name you will assign the generated function
so you must use Recall
for recursive calls.
linked_list := NIL | CONS(car, cdr : linked_list) lst <- CONS(1, CONS(2, CONS(3, NIL))) len <- case_trfunc(acc = 0, NIL -> acc, CONS(car,cdr) -> Recall(cdr, acc + 1) ) len(lst)#> [1] 3list_sum <- case_trfunc(acc = 0, NIL -> acc, CONS(car,cdr) -> Recall(cdr, acc + car) ) list_sum(lst)#> [1] 6