liveBook · Manning

Currying

As explained in The Well-Grounded Rubyist, Fourth Edition

Currying is a functional programming technique that transforms a function of multiple arguments into a sequence of functions that can be evaluated incrementally.

Currying transforms a multi-argument function into a sequence of functions that can receive arguments incrementally. In Ruby, Proc#curry uses a function's arity to delay evaluation until enough arguments arrive, returning another function along the way. section 16.3.4 section 16.3.5

Currying becomes clearer when contrasted with partial function application:

  • Partial application accepts fewer than the function's required arguments, evaluates the supplied portion, and returns one function for the remainder. section 16.3.5
  • Currying returns a series of functions, each taking one argument; Ruby's curry method supports both this behavior and partial application. section 16.3.5
  • Curried functions can be called directly with all arguments, incrementally with chained calls, or in mixed groups. section 16.3.5

Reusing a generic filtering function

Instead of defining separate functions for multiples of 3 and 5, define `find_multiples = -> (x, arr) { arr.select { it % x == 0 } }`. Calling `find_multiples.curry` and supplying 3 or 5 creates reusable functions that later accept an array and select its multiples. section 16.3.5

>> find_multiples_of = find_multiples.curry
>> find_multiples_of_3 = find_multiples_of.(3)
>> find_multiples_of_5 = find_multiples_of.(5)

Inspect the staged construction of specialized functions from a curried generic function, then apply them to arrays. section 16.3.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains arity, staged calls, partial application, and mixed argument groups, while stopping short of implementation internals.
Examples
Demonstrates addition, staged three-argument calls, variadic summation, method currying, and reusable array filtering.
What it assumes
Assumes familiarity with Ruby functions, Proc objects, lambdas, blocks, and argument arity.
What you can do after
Apply Ruby's curry method to build specialized functions from general Procs, lambdas, or methods.
How it connects
Links higher-order functions, partial function application, Proc objects, lambdas, arity, and immutable functional programming.

Also explained in

Compare how 7 books explain currying →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.