DEV Community

Discussion on: Function Currying, What's the use?

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

I believe the end goal of currying is partial application. Essentially, currying is how the function is structured, and partial application is what you can do with that structure.

The main reason you want to use partial application is with functions which take other functions as arguments. For example, Array.map.

const sayHello = offset => (name, index) =>
    return "Hello, " + name + ". Your number is " + (offset + index) + ".";

const names = [ "Deqwan", "Samir" ];
const offset = 5;

names
    .map(sayHello(offset))
    .forEach(console.log);

In the above, offset is curried. A non-curried equivalent would be.

const sayHello = (offset, name, index) =>
    return "Hello, " + name + ". Your number is " + (offset + index) + ".";

const names = [ "Deqwan", "Samir" ];
const offset = 5;

names
    .map((name, index) => sayHello(offset, name, index))
    .forEach(console.log);

In the latter example, it was necessary to make an adapter function for Array.map in order to use sayHello. Whereas in the previous example, all that was necessary was to partially apply an argument, and that resulted in a function that matched the signature of map.

In Javascript, currying is somewhat less compelling because most built-in functions are not curried, so using them may require extra adapter functions anyway. Plus, applying arguments requires parenthesis which is a bit of extra noise compared to commas. But it is still useful sometimes.

Sometimes devs use partial application in place of classes... it's equivalent to passing in a value to a constructor and keeping it as a private variable for subsequent method calls. But I don't care for this use case as much. I mainly use it for so-called "higher order" functions such as Array.map which take functions are arguments.

To be fair, I don't use Javascript much. I am speaking of when I use partial application in functional languages like Elm and F#. These languages are curried by default.