Bound Variable
# Compose

### Step 1

### Step 2

### Step 3

### Step 4

### Step 5

### Step 6

### Step 7

### Step 8

### Step 9

### Finally

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.

Look carefully. You see two functions.

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

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

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.

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.

Look carefully again.

times_15 = (n) -> times_3 times_5 n

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

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

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

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?

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`

.

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.