Types in lambda.r versus classes in S4

[This article was first published on Cartesian Faith » R, 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.

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 their blog: Cartesian Faith » R.

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)