The Cardinal Combinator

by Michael Ruggiero

Reading Raganwald’s book on combinators demonstrates how Ruby’s surprises slowly pay interest on your own understanding. You learn, not in the immediate, “Google lookup” kind of way (which I sort of do all the time), but in the creative “let’s try this and see what happens” way. In one of his examples of the “cardinal” combinator, Braithwaite shows a method that

do |a_proc| lambda { |a_value|
  a_proc.call(a_value) unless a_value.nil?
} end

Basic metaprogramming stuff, but when you dig farther into permuting the procs you get

def maybe(a_value, &a_proc) 
  lambda do |a_proc|
    lambda { |a_value| 
      a_proc.call(a_value) unless a_value.nil?
    } 
  end.call(a_proc).call(a_value)
end

Now, I love Python, but Python doesn’t offer a semantic world this rich. And it it doesn’t tempt me to try and create bizarre constructions that, while lacking practical import, encourage problem-solving in innovative, “why not?” ways. So while I may write deployment tasks in Python, the same old way I know how, when I want to play in IRB and “see what happens,” Ruby might have more for me, and I may only appreciate it in the very long run.