Skip to content

Higher Order functionsλ︎

Functions can be used as an arguments to other functions as we have seen in function composition. This is possible because a function always evaluates to a value. This is the basis of function composition.

Higher Order functions can also return a function definition, as when that function definition is evaluated it to will return a value.

You could have a function that returns a function definition which in turn returns a function definition, but at some point this will get very confusing for the developers (yes, that means you).

Note::Return the even numbers from 1 to 10λ︎

Generate a range of numbers from 1 to 10

Use a function that checks if a number is even and filter the range of numbers to return only the numbers that match


(filter
 even?
 (range 1 10))

Note::Create a named function as a higher order function called twiceλ︎

The function twice which takes a function and value as arguments.

The twice function should call the function passed as an argument on the value passed as an argument.

The result should be then used as an argument to calling the function passed as an argument again.

Call the twice function with an inline function which takes a number as an argument and adds it to Pi, 3.14.

(defn twice [f]
  ,,,)
;; Our higher order function

(defn twice [function x]
  (function (function x)))

(twice
  (fn [arg]
    (* 3.14 arg))
  21)
;; => 207.0516

;; using the short syntax for a function definition

(twice #(+ 3.14 %) 21)
;; => 207.0516

Note::Define a function that returns a functionλ︎

The function should take a clojure.core function for a mathematical calculation, i.e. +, -, *, /

The returning function should take one or more arguments [& args] and use the function originally passed as an argument to reduce the data to a single value.

(defn calculation [f]
  ,,,)
(defn calculation [f]
  (fn [& args]
    (reduce f args)))

((calculation +) 1 1 2 3 5 8 13)

;; The result of `(calculation +)` is also in a list,
;; so it will be called as a function, with the arguments 1 1 2 3 5 8 13

Referencesλ︎