Learn R Programming

trampoline (version 0.1.1)

trm_tailcall: Flag a tail call

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

trm_tailcall(x)

Arguments

x

A recursive call within generator fed to trampoline()

Value

x with added class attribute 'trampoline_tailcall'

Examples

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

Run the code above in your browser using DataLab