# [R] R and lazy evaluation

From: Russ Abbott <russ.abbott_at_gmail.com>
Date: Thu, 07 Apr 2011 21:08:06 -0700

> fibs <- c(0, 1, rep(0, 8))
> fibs[3:10] <- fibs + fibs[-1]

fibs = 0, 1, 0, 0, 0, 0, 0, 0, 0, 0
fibs = 0, 1, 0, 0, 0, 0, 0, 0, 0, 0

```fibs[3] <- fibs[1] + fibs[2]
fibs[4] <- fibs[2] + fibs[3]
fibs[5] <- fibs[3] + fibs[4]
```

etc.

In Haskell, the value of fibs[3] used to compute fibs[4] is the value just created by adding fibs[1] and fibs[2]. Similarly the value of fibs[4] used to compute fibs[5] is the value that was just created in the previous addition. In other words:

fibs[3] <- fibs[1] + fibs[2] # 0 + 1 = 1 fibs[4] <- fibs[2] + fibs[3] # 1 + 1 = 2  fibs[5] <- fibs[3] + fibs[4] # 1 + 2 = 3  fibs[6] <- fibs[4] + fibs[5] # 2 + 3 = 5  etc.

But if you actually carry out this calculation in R, this is you get.

>v <- c(0, 1, rep(0, 8))

>v

>v[3:10] <- v + v[-1]

1. In v + v[-1] :

longer object length is not a multiple of shorter object length

2: In v[3:10] <- v + v[-1] :

number of items to replace is not a multiple of replacement length

>v

Is there any way to make this work?

*-- Russ *

[[alternative HTML version deleted]]

R-help_at_r-project.org mailing list
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. Received on Fri 08 Apr 2011 - 04:10:52 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 08 Apr 2011 - 08:10:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.