# Re: [R] R and lazy evaluation

From: peter dalgaard <pdalgd_at_gmail.com>
Date: Fri, 08 Apr 2011 09:51:51 +0200

> 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, 0
>
> When one adds fibs to fibs[-1], one is effectively adding diagonally:
> fibs <- fibs + fibs
> fibs <- fibs + fibs
> fibs <- fibs + fibs
> etc.
>
> In Haskell, the value of fibs used to compute fibs is the value just
> created by adding fibs and fibs. Similarly the value of fibs used
> to compute fibs is the value that was just created in the previous
>
> fibs <- fibs + fibs # 0 + 1 = 1
> fibs <- fibs + fibs # 1 + 1 = 2
> fibs <- fibs + fibs # 1 + 2 = 3
> fibs <- fibs + fibs # 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
```

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

>
> Warning messages:
>
> 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
```

>
>  0 1 1 1 0 0 0 0 0 0
>
>
> Is there any way to make this work?
>

I should hope not.... (it would break call-by-value semantics, for one thing)

The closest you can get is something like

> delayedAssign("fib6", fib5+fib4)
> delayedAssign("fib5", fib4+fib3)
> delayedAssign("fib4", fib3+fib2)
> delayedAssign("fib3", fib2+fib1)
> delayedAssign("fib2", 1)
> delayedAssign("fib1", 0)
> fib6

 5

(you can construct those assignments programmatically in a loop with a little extra work.)

```--
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes_at_cbs.dk  Priv: PDalgd_at_gmail.com

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help