Re: [R] R and lazy evaluation

2011-04-09 Thread Russ Abbott
This solves the problem. fibs = function() { fibNumbers = 0:1 fib = function(n) { print(n) n[n<1] <- 1 cat("again: ", n, fill=TRUE) ifelse(n <= length(fibNumbers), fibNumbers[n], fibNumbers[n] <- fib(n-1) + fib(n-2)) } } >x <- fibs() >x(5:

Re: [R] R and lazy evaluation

2011-04-09 Thread Russ Abbott
I attempted to vectorize the preceding as follows. fibs = function() { fibNumbers = 0:1 fib = function(n) { print(n) ifelse(n <= length(fibNumbers), fibNumbers[n], fibNumbers[n] <- fib(n-1) + fib(n-2)) } } Unless I'm misunderstanding what's going on,

Re: [R] R and lazy evaluation

2011-04-09 Thread Russ Abbott
The following doesn't rely on lazy evaluation, but it accomplishes something similar by taking advantage of R's closure capability. >fibs = function() { fibNumbers = 0:1 fib = function(n) { if (n <= length(fibNumbers)) return(fibNumbers[n]) fibNumbers[n] <- fib(n-1) + fib(n-2) retu

Re: [R] R and lazy evaluation

2011-04-08 Thread Russ Abbott
Here's how to do it in Haskell. First define fibs to be an infinite list. Since Haskell is lazy, the list isn't actually created until needed. The function zipWith takes three arguments: a function and two lists. (It is similar to sapply except that it takes a function and two lists.) It applies

Re: [R] R and lazy evaluation

2011-04-08 Thread peter dalgaard
On Apr 8, 2011, at 06:08 , Russ Abbott wrote: > Haskell is the prototypical lazy evaluation language. One can compute a > Fibonacci sequence by the Haaskell equivalent of the following R code. > >> fibs <- c(0, 1, rep(0, 8)) >> fibs[3:10] <- fibs + fibs[-1] > > This works as follows. > > fibs

[R] R and lazy evaluation

2011-04-07 Thread Russ Abbott
Haskell is the prototypical lazy evaluation language. One can compute a Fibonacci sequence by the Haaskell equivalent of the following R code. > fibs <- c(0, 1, rep(0, 8)) > fibs[3:10] <- fibs + fibs[-1] This works as follows. fibs = 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 fibs = 0, 1, 0, 0, 0, 0, 0, 0, 0,