~ / track D / fp foundations

First-class functions

Basic

In Clojure, a function is just a value: you can store it in a variable, put it in a collection, pass it as an argument, and return it from another function. Functions that take or return other functions are called higher-order functions — they are the basic move of functional programming.

Minimal example

inc is an ordinary value bound to a function. Passing it to map is no different from passing a number to +:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

You can name anonymous functions with fn or the shorthand #(...). Both produce a value of the same kind as inc:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Practical example

A higher-order function abstracts the shape of a computation and lets the caller plug in the specific behavior. Here apply-twice doesn't know or care what f is — only that it can be applied:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Functions returning functions are equally ordinary. multiplier builds a new function tailored to a chosen factor:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Exercise

Write nth-power, a function that takes n and returns a function that raises its argument to the n-th power. Then use it with map to square the numbers 1..5.

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate
 status: new