Currying in Ruby

Update: while named after Haskell Curry, currying was actually developed by Moses Schoenfinkel and Gottlob Frege.

Currying is a technique in functional programming. Nothing mysterious though. Just a useful little way of building helper functions on the spot — you probably do it all the time without realizing (more on that in a moment).

Okay, see — mathemeticians once had this insight that:

lambda { |a, b, c| ... }

…means essentially the same thing as (for example):

lambda { |a| lambda { |b| lambda { |c| ... } } }

or

lambda { |a| lambda { |b, c| ... } }

In other words, conceptually you can break up a function’s arguments however you like. You don’t have to give them all at once. Apply a three-argument function to one argument? You get a two-argument function left over. Apply a three-argument function to two arguments, you get a one-argument function back.

Okay, so Ruby won’t break things up like that for you automatically, but you can do it explicitly with lambdas — say you want to curry two arguments into a three-argument function.

lambda { |c| zoog( 1, 2, c ) }

See? Two arguments curried in, one argument still dangling.

What use is this? Well, as I said you’ve probably done a lot of currying without realizing — many of the simple things people do with blocks amount to currying.

Look, we are currying:

blahs.map do |c|
  zoog( 1, 2, c )
end

…or more explicitly:

blahs.map &lambda { |c| zoog( 1, 2, c ) }

The thing about functional programming is that you are already doing it. It’s just a matter of learning to see the patterns and work with them.