Function Composition

We have discussed how functional programs are essentially a number of functions that work together, this is called composition (functional composition).

  1. (let [calculated-value (* 10 (reduce + (map inc (range 5))))]
  2. calculated-value)

This expression is common in the Lisp & Clojure languages. Occasionally the created expressions can becomes challenging to read. To overcome this parsing complexity, developers often break down a more complex expression into its parts, extracting code into its own function.

Note Brake down the above example into each expression that gives a value

  1. (range 5)
  2. (map inc (range 5))
  3. (reduce + (map inc (range 5)))
  4. (* 10 (reduce + (map inc (range 5))))
  5. ;; Additional examples
  6. ;; Use a let expression for code that is used more than once in a function
  7. (let [calculated-value (* 10 (reduce + (map inc (range 5))))]
  8. calculated-value)
  9. ;; Use defn to define a function for code that multiple functions will call
  10. ;; and generalise the function with arguments
  11. (defn common-data-calculation
  12. [certanty-factor scope]
  13. (* certanty-factor (reduce + (map inc (range scope)))))