What are other uses of functions as data?


#1

Question

In this exercise, the example of shortening a long function name to a short name is given as an application of using functions as data. In particular, we are given this example

is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;

This example seems artificial. Are there other examples where this is useful?

Answer

The use of functions as data in this way is helpful for at least two clear reasons.

  • First is that it enables us to pass functions as parameters to other functions. To be explicit, let’s say that we have two functions, makeSubarray and isEven.

    • makeSubarray accepts two parameters: an array arr and a function select which returns true or false depending on whether an array entry will be in the final array.
    • isEven has one parameter and returns true if it is even and false otherwise.

    We can implement this function as follows:

    function makeSubarray (arr, select) {
       return arr.filter(select);
    }
    

    and we can implement isEven just as simply by

    function isEven (n) {
       return n % 2 === 0;
    }
    

    The important thing to notice is that when we make a call to the makeSubarray function with an array, for example A = [0, 1, 2, 3, 4, 5], and isEven:

    makeSubarray (A, isEven); /* returns [0, 2, 4] */

    the makeSubarray function will essentially execute select = isEven before doing anything else so that the line

    return arr.filter(select);

    uses the correct function to create a subarray. So this way of using functions as data gives us callbacks.

  • Second and finally, there are cases where we write something like function1 = function2 to use the name function1 as a synonym for function2 when the name function1 is for some reason easier to type/remember than function2. The example doesn’t need to be as drastic as

    is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;

    but can be as simple as writing const dist = EuclideanDistance; when using a library that provides many different distance functions but you only plan to use the EuclideanDistance function and would prefer not to write it out completely multiple times – e.g. it may be obvious from context that the only distance function you could use is the euclidean distance.