Yes, it can

August 2, 2006
By

(This article was first published on "R-bloggers" via Tal Galili in Google Reader, and kindly contributed to R-bloggers)

Joel on Software’s latest post is about having first class functions in your programming language. He shows how you can use functions as arguments to functions to reduce code duplication. IReducing code duplication is a nice way to motivate language features since the process of removing duplication almost always results in improved code.

He also links first class functions to Google’s MapReduce. What doesn’t get mentioned is how first-class functions play with closures (lexical scope) and how powerful these notions are when put together.

You can use this in a duplication reducing way to simplify repeated function calls where only a few of the parameters change. For example:

foo(a, b, c, “yes”)
foo(a, b, c, “no”)
foo(a, b, c, “maybe”)

myfoo <- function(a, b, c, ans) {
function(ans) {
foo(a, b, c, ans)
}
}

myfoo("yes")
myfoo("no")
myfoo("maybe")

You can also use lexical scope to maintain state across function calls. This one is perhaps less interesting since in most OO languages, this sort of thing is done via classes.


callCounter <- function() {
count <- 0
function() {
print(paste("I've been called", count, "times"))
count <<- count + 1
}
}

countCalls <- callCounter()
> countCalls()
[1] “I’ve been called 0 times”
> countCalls()
[1] “I’ve been called 1 times”
> countCalls()
[1] “I’ve been called 2 times”
>

To leave a comment for the author, please follow the link and comment on his blog: "R-bloggers" via Tal Galili in Google Reader.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags:

Comments are closed.