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:
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,
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
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
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
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,
6 matches
Mail list logo