Yes, it can

August 2, 2006

(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)


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 their blog: "R-bloggers" via Tal Galili in Google Reader. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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...


Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Dommino data lab

Quantide: statistical consulting and training



CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)