In order to appreciate the utility of first-class functions, we need to properly understand what “functional programming” is first.
First-class functions are functions that can be used wherever we can use values.
<aside> 🆙 A function that takes a first-class function as an argument is known as a higher-order function. Higher-order functions are very useful in storing code that will be reused (with different first-class functions as arguments).
</aside>
Functions can be passed as arguments to other functions.
fun f (g...) = ... g (...) ...
fun h1 ... = ...
fun h2 ... =
... f (h1,...) ... f (h2,...) ...
In what situations do we use functions as arguments?
When we have multiple functions which share similar structures, we can factor out the structure and replicate the functionality of the original functions through the use of a higher-order function.
In the words of Dr. Grossman:
”Replace N similar functions with calls to 1 function where you pass in N different (short) functions as arguments”
In the example above, the “similar” functions are the “lame” functions, the common function is n_times
, and the short functions used as arguments are incr
, double
, and tl
.