Types in lambda.r versus classes in S4

July 10, 2013
By

(This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers)

Here’s a quick example of the power of lambda.r and how it simplifies the programming model. On the r-devel mailing list, someone gave an example of extending a class via S4. It looks like this.

setClass("foo", contains = "Date")
setMethod("+", c("foo", "difftime"), function(e1, e2) callNextMethod())

This new class foo can then be used like a Date.

x <- new("foo", as.Date("2013-06-30"))
> dt <- as.difftime(1, units = "days")
> x + dt
[1] "2013-07-01"

Using S4 has always struck me as being way too complicated. I could never remember the syntax, nor did I find it particularly enjoyable to write. On the other hand, with lambda.r, it is easy to extend a native type and make use of it.

Foo(x) %as% as.Date(x)

Usage of this type is also cleaner as the constructor is simpler.

> x <- Foo('2013-06-30')
> dt <- as.difftime(1, units = "days")
> x + dt
[1] "2013-07-01"

This example demonstrates how lambda.r captures one aspect of literate programming by using a syntax that reads like simple exposition.


To leave a comment for the author, please follow the link and comment on his blog: Cartesian Faith » R.

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...

Comments are closed.