[R] Simulation
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu May 14 12:53:41 CEST 2009
Peter Flom wrote:
>
>>> Seriously? You think:
>>>
>>> lapply(1:n, rnorm, 0, 1)
>>>
>>> is 'clearer' than:
>>>
>>> x=list()
>>> for(i in 1:n){
>>> x[[i]]=rnorm(i,0,1)
>>> }
>>>
>>> for beginners?
>>>
>>> Firstly, using 'lapply' introduces a function (lapply) that doesn't
>>> have an intuitive name. Also, it takes a function as an argument. The
>>> concept of having a function as a parameter to another function is
>>> something that a lot of programming beginners have trouble with -
>>> unless they were brought up on LISP of course, and few of us are.
>>>
>>> I propose that the for-loop example is clearer to a larger population
>>> than the lapply version.
>>>
>
>
> As a beginner, I agree .... the for loop is much clearer to me.
>
>
well, that's quite likely. especially given that typical courses in
programming, afaik, include for looping but not necessarily functional
stuff -- are you an r beginner, or a programming beginner?
among the perl packages i have ever downloaded from cran, it's hard to
find one without a for loop, but it's easy to find one without a map.
but it's not necessarily because for loops are easier; just that that's
the way people are typically taught to program.
the structure and interpretation of computer programs (sicp) by abelson
& sussman, a beautiful cs masterpiece, introduces mapping (lapplying) on
p. 105, mentions a for-each control abstraction only in an exercise two
pages later, and does not really discuss for looping as such.
functional mapping over stateless objects is, in general, *much* easier
to reason with than procedural looping over stateful objects -- an issue
a beginner may not be quite aware of, and learning the basic for loop
stuff without caring about, e.g., concurrent access to shared mutable
state etc. may indeed make the impression that for loops are easier.
anyway, once you've learned for loops, it's not a bad idea to learn
lapply. and once you've learned lapply, you'll probably not go back to
for loops that easily.
vQ
More information about the R-help
mailing list