An alternative implementation, closer to what I need when I have more than one 
recursion in each step, but still using factorial as the example, is this one:

thunk_factorial <- function(n, continuation = identity) {
  force(continuation) # if I remove this line I get an error
  cat("call: ", n, "\n") # same for this line
  if (n == 1) {
    continuation(1)
  } else {
    new_continuation <- function(result) {
      cat("thunk: ", result, "\n”) # remove this line and it fails, keep it and 
it works
      make_thunk(continuation, n * result)
    }
    make_thunk(thunk_factorial, n - 1, new_continuation)
  }
}
trampoline(thunk_factorial(10000))

Here I am making a continuation instead of passing along an accumulator, which 
I need to do for more complex cases, and with that continuation I can also get 
it to complete without errors if I output the text inside it. Removing the 
`cat` line and I get the recursion error…

Cheers
        Thomas



> On 10 Aug 2016, at 18:53, Thomas Mailund <mail...@birc.au.dk> wrote:
> 
> 
>> On 10 Aug 2016, at 13:56, Thomas Mailund <mail...@birc.au.dk> wrote:
>> 
>> make_thunk <- function(f, ...) f(...)  
> 
> Doh!  It is of course this one:
> 
> make_thunk <- function(f, ...) function() f(…)
> 
> It just binds a function call into a thunk so I can delay its evaluation.
> 
> Sorry
>       Thomas
> 
> 
> 
> ______________________________________________
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to