trm_tailcall: Flag a tail call

Description Usage Arguments Value Examples

View source: R/trampoline.R

Description

If you can specify your recursive function such that the recursive call is in 'tail position' (that is, the very last operation in your function), you can take advantage of tail call optimization. Just wrap your recursive call in trm_tailcall()

Usage

1

Arguments

x

A recursive call within generator fed to trampoline()

Value

x with added class attribute 'trampoline_tailcall'

Examples

1
2
3
4
5
6
7
8
9
trampoline(factorial(13),
           factorial = function(n, x = 1) {
             force(x) ## necessary thanks to R's lazy evaluation
             if(n <= 1) {
               return(trm_return(x))
             }
             val <- trm_tailcall(factorial(n - 1, x * n))
             return(val)
           })

trampoline documentation built on Jan. 5, 2022, 1:07 a.m.