liveBook · Manning

Higher-order function

As explained in The Well-Grounded Rubyist, Fourth Edition

A higher-order function is a function that takes another function as an argument or returns a function as its result.

A higher-order function takes another function as an argument or returns a function as its result. In Ruby, blocks and procs provide these function values: methods such as map and inject/reduce accept blocks, while methods can return procs. section 16.3 section 16.3.4

Ruby uses higher-order functions to express several recurring patterns:

  • Transform or filter collections by passing a block to methods such as map or select. section 16.3
  • Return transformation instructions in a proc, then call that proc after additional information becomes available. section 16.3.4
  • Abstract varying arguments with currying, which returns partially applied functions until enough arguments have been supplied. section 16.3.5
  • Combine generic functions with lazy enumerators to produce concise computations over potentially unbounded sequences. section 16.4.1

From duplicated methods to a reusable function

Separate methods can find multiples of 3 or 5, but a generic function accepts the divisor and the array: `find_multiples = -> (x, arr) { arr.select { it % x == 0 } }`. Currying specializes the first argument: `find_multiples_of_3 = find_multiples.curry.(3)`. Supplying an array later produces the matching values. section 16.3.5

>> [1,3,5].map { |x| x * 5 }
=> [5, 15, 25]

Run a compact Ruby example showing a block passed to map and the resulting transformed array. section 16.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block arguments, returned procs, currying, partial application, calling forms, arity, and lazy higher-order computations.
Examples
Demonstrates map, multiplier procs, curried multiple-finding functions, addition, lazy squares, and recursive sums of powers.
What it assumes
Assumes familiarity with Ruby methods and blocks while developing procs, returned functions, lambdas, currying, and lazy enumeration.
What you can do after
Build it from scratch by passing blocks, returning procs, and using currying to create reusable functions with delayed arguments.
How it connects
Connects higher-order functions with blocks, procs, lambdas, map, inject/reduce, currying, partial application, lazy evaluation, and recursion.

Also explained in

Compare how 14 books explain higher-order function →

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.