Curry and partial application
A closure (Phase 6) doesn't just hide private state - it can also hold onto
an argument for later. Partial application means fixing one argument now
and getting back a smaller function that only needs the rest. Currying
takes that idea further: a function that normally takes several arguments is
rewritten to take them one at a time, each call returning a new function
until enough arguments have arrived.
The trick is a single if: check whether the second argument showed up. If
it did, you have everything you need - finish the job now. If it didn't,
return a new function that remembers the first argument (through a closure)
and waits for the rest.
Your task: write add(a, b) so it works both ways - add(2, 3) returns
5 immediately, and add(2)(3) also returns 5, by returning a function
that remembers 2 and waits for the second number.
You'll practice:
Checking whether an argument was actually passed
Returning a function that closes over an already-received argument
Show a hint
Show solution
Related reading: Closures You'll Actually Write →
Previous Next