Currying with Procs
The word “curry” comes from the mathematician Haskell Curry. (I am resisting all attempts to make a lame joke about an Indian dish.) In functional programming, currying is the process of turning a function that takes n arguments into one that takes a single argument, but returns n functions that take one argument.
For example, given a lambda that accepts three parameters:
| >> discriminant = lambda { |a, b, c| b**2 - 4*a*c } |
| |
| >> discriminant.call(5, 6, 7) |
| => -104 |
you could convert it into this:
| >> discriminant = lambda { |a| lambda { |b| lambda { |c| b **2 - 4*a*c } } } |
| |
| >> discriminant.call(5).call(6).call(7) |
| => -104 |
In Ruby, there’s a shorter way to do this using Proc#curry:
| >> discriminant = ... |
Get Mastering Ruby Closures now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.