Yes, it can

[This article was first published on "R-bloggers" via Tal Galili in Google Reader, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: "R-bloggers" via Tal Galili in Google Reader.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)