Jun 24 2008
Functional (Meta)?Programming Stunts for Ruby and Groovy (and a Little Perl)
After I learned OCaml, my coding mindset was totally distorted. I started writing Java code that looked like this:
public Collection<Foo> getCertainFoos() { return CollectionUtils.select(getFoos(), new Predicate() { public boolean evaluate(Object o) { return SOME_CONSTANT.equals(((Foo)o).getProperty()); } }); }
This is kinda ugly in Java, but it’s simply what comes out when I was thinking this in OCaml:
List.find_all (fun i -> SOME_CONSTANT = i#getProperty()) #getFoos()
I also started slapping final everywhere — see Yet Another Reason final Is Your Friend. A ubiquitous use of final actually gave some nice patterns (in the “macro” sense of patterns), but raised all kinds of eyebrows and made my code unmistakable. This lead up to a unique coding style which you can see in my most involved open source project, JConch. Meanwhile, my co-blogger was talking about “The Hole in the Middle” Pattern, which is also a lay-up within FP circles but required some backflips to implement in Java (functional interfaces) and C# (delegates).
It wasn’t until the advent of Ruby and Groovy, though, that functional programming skills really became easier to use. Basically, because of the inline closure’s succinct syntax (and ability to access non-final variables), I could suddenly do all kinds of really fun stuff. This “fun stuff” was exactly the kind of stunts I was pulling in Perl back in the day (see the BEGIN block in my Text::Shift code for a reasonably accessible example), and it was part of the reason I loved Perl so much at the time.
So, I thought I’d share some more of these cute stunts with you.
Continue Reading »
Popularity: 6% [?]