1

Im following this course and came across this problem

const compose = (f, g) => (a) => f(g(a));
const add1 = (num) => num + 1;
const add5 = (num) => num + 5;
compose(add1, add5)(10)

As i understand it g(a) gets run first so num = 1 makes 1 for g and 10 for a, that makes it f(1(10)). But how does the 1 and the 10 know to add, why doesn't it multiply or minus ?

1
  • 5
    compose(add1, add5)(10) -> a === 10, g === add5, f === add1 -> add1(add5(10)) Commented Jan 4, 2020 at 13:18

2 Answers 2

4

that makes it f(1(10))

This is not true. Because 1(10) is not even a valid javascript syntax. When the value 10 is passed to the function g its returns five more than the value which is 15. This is because its defined in the function add5 which is passed as g to the compose function

The value returned from the above function call which is 15 is then passed to f which is add1. So in the last it returns 16

But how does the 1 and the 10 know to add, why doesn't it multiply or minus.

You are using + inside the functions passed. If you will use - or * it will then multiply or minus

Sign up to request clarification or add additional context in comments.

4 Comments

"g its returns one more" should be "g it returns five more"
ive tried to replace with a * or - in a console and it says its invalid syntax
What you replaced with * or -, You need to replace + in side the function
@JohannDavelDeBeer const add1 = (num) => num * 1;
-1

This is a technique known as currying.

Your compose function takes two functions as arguments.

Those functions each take a single num argument.

When you call compose(add1, add5)(10) the expression is parsed as the following:

Give me the output of calling add1 on the output of calling add5(10). In Javascript syntax, this looks like, f(g(a)), i.e. add1(add5(10)).

If you follow and evaluate the expressions in order, it goes:

compose(f, g)(a) === f(g(a))

compose(add1, add5)(10) === add1(add5(10)) === add1(15) === 16

2 Comments

There's no currying going on in any of this code. An example of currying would be const add = x => y => x + y; add(1)(2); // -> 3. What we have in this sample code is simply the composition of two unary functions.
"This is a technique known as currying." this is simple classical functional composition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.