First-class functions
BasicIn 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
incclojure.core/incAdd one.view on clojuredocs → is an ordinary value bound to a function. Passing it to mapclojure.core/mapApply f to each element, returning a lazy seq.view on clojuredocs → is no
different from passing a number to +:
You can name anonymous functions with fnclojure.core/fnAnonymous function: (fn [args] body).view on clojuredocs → or the shorthand #(...). Both
produce a value of the same kind as incclojure.core/incAdd one.view on clojuredocs →:
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:
Functions returning functions are equally ordinary. multiplier builds a new
function tailored to a chosen factor:
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 mapclojure.core/mapApply f to each element, returning a lazy seq.view on clojuredocs → to square the numbers
1..5.