Compose


The cliché goes that you either get it or you don’t. Once you know how the magician does his trick it’s not magic anymore. Usually, it’s not even a trick, you just weren’t looking at what you needed to.

Step 1

Look carefully. You see two functions.

times_3 = (x) -> x*3
times_5 = (x) -> x*5

Step 2

Now you see a variable n and another variable n_times_3 assigned as the result of invoking times_3 with the value of the variable n.

n = 4
n_times_3 = times_3 n

Step 3

Now you see the variable n_times_3_times_5 assigned as the result of invoking the function times_5 invoked with the value n_times_3.

n_times_15 = times_5 n_times_3

Take a value. Pass it to a function. Get the result. Pass it to another function. Get the result.

Step 4

Look carefully again.

n = 4
n_times_15 = times_3 times_5 n

Now the intermediate variable n_times_3 is gone.

Stop looking at the variables.

Step 5

Look carefully again.

times_15 = (n) -> times_3 times_5 n

Step 6

You don’t always want to times by 3. Perhaps sometimes you want to times_2, or times_8. Pass the function in as an argument:

times_x_times_5 = (n, times_x) -> times_5 times_x n

Step 7

You don’t always want to times by 5 either.

times_x_times_y = (n, times_x, times_y) -> times_y times_x n

Step 8

Now, forget about what the functions do. What is the general pattern?

Look carefully.

fg = (k, f, g)  -> f g k

You know how to use this function.

n = 4
fg n, ((x) -> x*3), ((x)-> x*5)

The result is 60. That’s 5 * 4 * 3.

A function that takes three arguments is inconvenient. What can you do?

Step 9

Write a new function that takes the first two arguments and returns a new function that takes the third argument.

Look carefully.

cfg = (f, g) ->
  (x) -> f g x

You can use this to create a times_15 function.

times_15 = cfg times_3 times_5

So you see that one way to express times_15 is as the composition of times_3 with times_5.

Finally

It is called compose.

compose = (f, g) -> (x) -> f g x

Until you see this without steps 1 to 9 you are not ready for combinators.



CoffeeScript in Action


CoffeeScript in Action book cover

I'm the author. Get it from Manning.