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 ```eval-clojure

  1. <!--sec data-title="Return the even numbers between 1 and 10" data-id="answer002" data-collapse=true ces-->

(filter even? (range 1 10))

  1. <!--endsec-->
  2. > #### Note::Create a named function as a higher order function called `twice`
  3. > The function twice which takes a function and value as arguments.
  4. >
  5. > The twice function should call the function passed as an argument on the value passed as an argument.
  6. >
  7. > The result should be then used as an argument to calling the function passed as an argument again.
  8. >
  9. > Call the twice function with an inline function which takes a number as an argument and adds it to Pi, `3.14`.
  10. ```eval-clojure
  11. (defn twice [f]
  12. ,,,)
  1. ;; Our higher order function
  2. (defn twice [function x]
  3. (function (function x)))
  4. (twice
  5. (fn [arg]
  6. (* 3.14 arg))
  7. 21)
  8. ;; => 207.0516
  9. ;; using the short syntax for a function definition
  10. (twice #(+ 3.14 %) 21)
  11. ;; => 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.

  1. (defn calculation [f]
  2. ,,,)
  1. (defn calculation [f]
  2. (fn [& args]
  3. (reduce f args)))
  4. ((calculation +) 1 1 2 3 5 8 13)
  5. ;; The result of `(calculation +)` is also in a list,
  6. ;; so it will be called as a function, with the arguments 1 1 2 3 5 8 13

References