DEV Community

Discussion on: βœ”||🀒 Commit or Vomit | function currying πŸ›

Collapse
 
sargalias profile image
Spyros Argalias • Edited

Currying on its own is simply a way to do partial application. Nothing more, nothing less. (Unless you subscribe to the fact that your code is easier to prove mathematically if your functions only accept one argument. But I've never had my code mathematically proven in my professional work.)

For example:

import {multiply} from 'somewhere';

// with currying
const double1 = multiply(2);

// partial application without currying
const double2 = (number) => multiply(number, 2);

// inline is shortest because you don't have to import
const double3 = (number) => number * 2;
Enter fullscreen mode Exit fullscreen mode

As you can see, the curried implementation is slightly cleaner and shorter if you need to do partial application (fix arguments on an already defined function). For complicated functions, you need to do partial application. You can't just redefine them inline every time you need them.

But as you can see, the benefit is small.

But, in programs written in a functional programming style, we do this a lot, so the little cleanliness of currying adds up.

For example:

// with currying
const operation = compose(baz(7), bar(5), foo(2));

// with normal partial application
const operation = compose((number) => baz(7, number), (number) => bar(5, number), (number) => foo(2, number));

// with imperative code
function operation(number) {
  const result1 = foo(2, number);
  const result2 = bar(5, result1);
  const result3 = baz(7, result2);
  return result3;
}
Enter fullscreen mode Exit fullscreen mode

So yeah, small benefit overall, but can make some things cleaner if you're used to the syntax.

Hope this is somewhat useful, even if it wasn't asked for :).

Collapse
 
jmdejager profile image
🐀πŸ₯‡ Jasper de Jager

Wow thanks! Great example and clear explanation, really useful ☺️