liveBook · Manning

Higher-order function

As explained in Learn Haskell by Example

A higher-order function is a function that receives one or more functions as arguments or returns a function as its result.

A higher-order function receives another function as an argument or returns a function. It separates an algorithm’s general structure from the specific behavior supplied by the caller. section 2.5.1

A list transformation demonstrates the pattern: traverse the list once, apply the supplied function to each element, and construct the result. The same transformation can increment numbers, test values, or replace characters. section 2.5.1

A reusable list transformation

transform :: (t -> a) -> [t] -> [a] transform fun [] = [] transform fun (x : xs) = fun x : transform fun xs transform (\x -> x + 1) [1..10] produces [2,3,4,5,6,7,8,9,10,11]. Applying a predicate produces [Bool], while applying a character replacement produces "Hullo World!".

Parametric polymorphism makes higher-order functions reusable across element types. The type variable t allows transform to consume one kind of element while a may differ for the produced elements. section 2.5.2

Functions are values, so a program can select behavior by storing one of several functions in a variable. A line-numbering tool uses this technique to choose between numbering all lines and numbering only nonempty lines. section 4.4.1

Use higher-order functions to:

  • Describe a general operation over a data structure. section 2.5.1
  • Replace repeated, type-specific implementations with one polymorphic function. section 2.5.2
  • Generalize similar graph operations over lists, such as adding edges and building a directed graph. section 5.3.1

How Learn Haskell by Example covers it

How deep it goes
Defines the abstraction, implements recursive list traversal, checks polymorphic types, and applies functions in a command-line tool.
Examples
Uses numeric increments, predicates, character replacement, line-numbering choices, and graph-function generalization.
What it assumes
Uses lists, recursive functions, function types, Boolean expressions, and algebraic data types.
What you can do after
Build reusable polymorphic list transformations and switch application behavior by selecting functions at runtime.
How it connects
Connects higher-order functions with lists, parametric polymorphism, type inference, algebraic data types, and command-line options.

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 Learn Haskell by Example. The section links point to the parts of the book it draws on.