Composition Exercise: Challenge 3
// -- Challenge 3 -------------------------
// There is more to point-free programming
// than compose! Let's build ourselves
// another function that combines functions
// to let us write code without glue variables.
var fork = _.curry(function(lastly, f, g, x) {
return lastly(f(x), g(x));
});
The task is to get the average from a list. You need to get two facts about the list: the length and the sum. With compose this is very hard (not possible). You get the sum from the first function, but then you don't have the list length anymore.
fork
fork takes two functions, calls both with the same arguments and then calls the next function (
lastly
) with the two results.
// As you can see, the fork function is a
// pipeline like compose, except it duplicates
// its value, sends it to two functions, then
// sends the results to a combining function.
//
// Your challenge: implement a function to
// compute the average values in a list using
// only fork, _.divide, _.sum, and _.size.
var avg = _.identity; // change this
assertEqual(3, avg([1,2,3,4,5]));
The solution with fork
var avg = fork(_.divide, _.sum, _.size)
Curried (here) means that the function has been called, but was not given all of the arguments (x
) and waiting for the last one. Brian explains that this fork
stuff will be replaced by other applicative functors later in the course.