With Ruby 1.9 sneaking up on us, it’s probably time to start getting excited about new features, so here goes. Ruby 1.9 has a completely new syntax for lambdas that maps perfectly onto actual lambda calculus.
Crash course in lambda calculus: Generally speaking, expressions are specified as “(λ parameters. result) argument”, everything is left-associative, and functions are called like “f v”, where f is a function and v is a value (or a function…) Thus, the expression:
(λ f. f 3) (λ x. x + 2)
evaluates to 5, since the expression on the left consumes a function and calls it with the value 3, while the expression on the right returns its argument plus two. Note that referring to values and functions as two distinct concepts here is technically incorrect, but helps to explain what happens. To do the same thing in Ruby 1.8.7, one would write:
# Ruby 1.8.7
lambda{|f| f[3]}[lambda{|x| x+2}]
In Ruby 1.9, some new syntactic sugar has been added:
# Ruby 1.9
->(f){f.(3)}.(->(x){x+2})
The “->” is supposed to be read as a lambda (λ), since relying on unicode characters in code is generally bad news. Not only is this significantly less syntactic overhead than the equivalent code in 1.8.7, it feels less like an ugly hack and more like an acutally-supported feature.
# λ x. x
->(x){x}
I hope this new lambda syntax encourages more people to write ruby with a more functional style. At the moment, it’s certainly an underused ‘facet’ of ruby.
6 Comments until now
Nice article Burke. I’m currently learning Functional programming (and consequently Lisp) in school and I will definitely be playing with Lambda’s more often from here on in.
I prefer the Haskell syntax.
(\f -> f 3) (\x -> x + 2)
Same, you can also use proper arrows,
Prelude> :set -XUnicodeSyntax
Prelude> (\ f → f 3) (\ x → x + 2)
5
Wow. That’s almost enough to make me go for round 2 at learning Haskell.
I keep trying to learn real functional languages like Haskell, Erlang, and CL, then getting distracted by how, as I then discover, I can actually do most of the stuff I want in Ruby.
I’m not going to pretend that this is a particularly elegant way of handling lambdas, even post-syntax-update, but it’s an improvement for Ruby, at least.
I think all the syntaxes are butt ugly. I would rather use unicode and the real lamba.
Having Unicode syntax that closely tracks what math majors use would be great even if it’s just an alternative. You can patent mathematic expressions, so the less computer languages hide their heritage as mathematic expressions, the less defensible such code would be to a patent challenge. Yes, 8-bit code is so much simpler to compile than Unicode code, but Ruby is up to the challenge if they wanted to pursue it.
Add your Comment!