DEV Community is a community of 862,249 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Discussion on: What the heck is Currying anyway?

Ken Aguilar • Edited on

Cool post! The motivation behind currying came from lambda calculus. In lambda calculus, you can only have anonymous unary functions. That means your function can only take one parameter and there's no way of calling other functions because they're anonymous, so the only way to do it is by nesting your function calls, a.k.a currying.

Here's the identity function. It takes 1 argument and returns it.

``````λx.x
``````

In pseudo javascript this looks like

``````(x) => x
``````

What if we want the Kestrel/K combinator? In javascript, it can be expressed like this

``````(x, y) => x
``````

But how would we do that in lambda calculus? By calling another lambda expression.

``````λx.(λy.x)
``````

In javascript, this will look like

``````(x) => (y) => x
``````

So, in javascript it looks like you can just have more arguments in your function. Why would you want to do currying if it's capable of taking in more than one argument? Well.. the cool thing about curried functions combined with naming them, is you can partially apply them.

``````const addNum = x => y => x + y
// y => 1 + y
const myNum = addOne(10)
// 11
const myNiceNum = addOne(69)
// 70
``````

And because you're using unary functions it's easier to identify the cardinality of each function.

EDIT: Using the above example with a compose function... coz partially applied functions with composition is pretty cool

``````const compose = (...fns) => (arg) =>
fns.reduceRight((acc, fn) => (fn ? fn(acc) : acc), arg)