DEV Community

Cover image for Currying in JavaScript

Currying in JavaScript

Suprabha on July 08, 2020

Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. ...
Collapse
 
jwp profile image
John Peters

Thanks for excellent simple explanation. However I must admit I see no valid reason for this pattern. It hides outcomes based on parameter counts, but later remembers prior values? It's like a dynamic function with pre determined state. What would the test pattern look like?

Collapse
 
wulymammoth profile image
David • Edited

This is a fair thought and/or assumption. I think the OP’s post is illuminating more so how it is done rather than how or why it could be useful or valuable. It would confuse the unacquainted if presented in a code based with those unfamiliar with the functional paradigm, too.

However, the value that I see in currying and partial application is composition — yeah... instead of writing an addTwo, addThree, addFour, addFive. It can simply be composed of a curried function. We use composition all the time by trying to perform code-reuse. Currying and partial application is just another tool or enabler and very standard in more purely functional languages — as we begin to think how we can make something with a sum of parts rather than building that something from scratch over and over again. If you’ve ever used underscore or the lodash libraries, Lodash declares its parameters in a very particular order to support this whereas underscore, unfortunately, does not. I’m on my phone so I cannot show the adder examples with code snippets but they can easily be found online.

Testing is simple — similarly to any unit test where we test what the expected behavior should be and they are: with no arguments supplied, some arguments supplied, and all arguments supplied and assert those outcomes

Collapse
 
jwp profile image
John Peters • Edited

See my better example below to point out how the 1 is hidden and no debugging will help determine where it came from.

Thread Thread
 
wulymammoth profile image
David • Edited

I'm not sure that I follow your example... if you've a function that reads sum, you expect it to produce a "sum". Right?

State is only relevant if it's mutable. If you supply an object with mutable state to a partially applied function, we're in for a debugging nightmare. I would even go so far as to say it's one of the reasons functional ideas have lackluster adoption in JS, unless we're dealing with scalar values or objects with immutable state.

Let's say that we have a function that helps us compute the size of a park plus some "buffer" that is only supplied at the time of construction, but we don't yet know before hand. We want to maintain a very specific interface: courts are supplied somewhere early in the process, but we expose to the builder only one parameter -- the buffer. They need not worry about courts and sizes, it is done somewhere earlier and up the chain.

function parkSize(courts) {
  return function(buffer) {
    return sum(courts) + buffer;
  }
}
Enter fullscreen mode Exit fullscreen mode

My example isn't very hard to test is it? The set-up involves two steps:

  1. supply court objects
  2. supply a buffer
  3. make an assertion

With the contrived example I have. I can "compose" a new function that exposes a "limited" and easy to understand interface for someone that needs to determine "recreational areas":

var courts = [...];
var parkArea = parkSize(courts); 
var buffer = 100; 
function recreationalSpace(buffer, privateSpace) {
  return sum(parkArea(buffer)) - privateSpace;
}
Enter fullscreen mode Exit fullscreen mode

This is no different than you using a library that's pre-configured -- you don't need to know all the default values before using it; one can infer based on the interface that's exposed. Otherwise, we could push for writing procedural imperative code that's all in a single file. How testable would that be?

Currying and partial application allow the designer/developer to control when arguments are supplied, otherwise you could end up having an outsized parameter list which forces the consumer of the function to know about the entire world at point of conception (runtime). The consumer of the function need not know about everything that was configured/supplied before it. Just like you don't need to know about all the internals of the library before you can use it. The only thing that should be implicit is the name of your function and what it's trying to convey... in the context of OOP, we this idea captured as well, called "encapsulation" -- prevent direct access to data except through a predetermined interface (methods). We don't want abstraction leaks and data access from everywhere. The consumer should need not know about the implementation details.

Every function that I've declared should be tested, so that if something is odd (like a bug), I know immediately where to look and what assumptions were made. It's really no different from us using a library that's hopefully well tested. We build tests upon a combination or composition of our own assumptions about what a library provides for us. In fact some of the libraries people use in JavaScript have functions that are exposed that are partially applied. You never need to dig into them unless seemingly unexpected behavior is exhibited after checking our own code...

Thread Thread
 
jwp profile image
John Peters • Edited

Thanks David I did some debugging today to figure this out.

 function sum(a) {
      return function (b, c) {
        return a + b + c;
      };
    }

    let mysum = sum(1);
    debugger;
    let mysum2 = mysum(2, 3);
    debugger;
Enter fullscreen mode Exit fullscreen mode

The results were:

As we can see, if a debugger wanted to know the value of mysum, in the console, they would only see it's a function as shown on far right side.

There's zero indication that this function when executed the 2nd time, has a preset value of 1 in it.

Now assume that mysum was set on entry to a module, but mysum2 was set much later. The developer is now wondering how mysum2 = 6...

mysum and mysum2 give no answers, but creating a de-composed form as shown in mysum3 kind-of, sort-of does help the debugger to understand.

This is what I was struggling with and why I mentioned an implicit state..

mysum is not a value, it's a function pointer! No values are returned until the 2nd and 3rd parameters are passed in. So this shows us that returning multiple functions forces a bit of thinking differently, as was said earlier it's composition of functions. Expressed in this syntax most clearly

let mysum3 = sum(1)(2,3);
Enter fullscreen mode Exit fullscreen mode

Indeed anonymous functions at that! I've seen this syntax before; but until now, didn't fully understand it.

Thanks!

Thread Thread
 
wulymammoth profile image
David • Edited

Ah! I love that your curiosity made you do a deeper dive! I went through something similar in other languages and honestly have never done currying or partial application in JS, although I've wanted to when I was spending most of my time in it.

Implicit state is always there, when you're working with a function that has had some arguments partially applied "earlier on". Does it make debugging more difficult? Yeah, it's not as easy as just shoving a break-point and inspecting current state. In languages, like Haskell, the lazy-evaluation becomes a challenge but yields performance gains. I work in Elixir which has nice facilities for this type of introspection, because it allows one to perform eager or lazy evaluation (Enum vs Stream) with the same functions in both modules

But I guess you're right, though -- that this idea (currying and partial application) isn't that useful in JS because it isn't the default paradigm that most of us are operating in. If employed, it would be analogous to using regexes everywhere and having to constantly explain them to everyone else. I very much like the ideas behind "functional reactive programming" ala RxJS where everything is a stream enabling some really really neat things one can do, but it is tough to get organizational buy-in when outside of some skunk-works team or small shop. But it is a powerful tool to maximize code reuse and a composition enabler in other languages and paradigms though

Collapse
 
jesuscovam profile image
jesuscovam

I think the same, but It could be useful for when a param must be computed from other functions, that you might already wrote outside the currying, sor I just my use like this currying(1)(resultOf(2))(3). That's my take in my head.

Collapse
 
jwp profile image
John Peters • Edited

Nice, this makes for placeholder to inject the results of functions.

However, we are also able to do this:

someFunction(1, get2ndParm(), 3);  Which is shorter.

Also, wouldn't currying break the pure function pattern?

Thread Thread
 
macsikora profile image
Pragmatic Maciej

Currying is not pattern. It is function property. In all FP languages functions are like that, so they are curried.

If you have function f: a ->b->c then by applying only a we have function g: b->c.

In JS as it's not FP language we need to make currying manually by using closures and returning function from function. It doesn't violate any purity as it is exactly FP concept.

Thread Thread
 
jwp profile image
John Peters

But has no value as far as I can tell.

Thread Thread
 
macsikora profile image
Pragmatic Maciej

If it would not have value it would not exists. It has huge value. But this answer would be worth a whole post about that ;)

Thread Thread
 
jesuscovam profile image
jesuscovam

maybe the second function would need a valued computed from the first function, so it could be use as a pipeline of computed values that are reusable and can be rearranged as legos

Collapse
 
pentacular profile image
pentacular

It's a way to make function interfaces uniform, so that a function becomes a transform from one input value to one output value.

Collapse
 
jwp profile image
John Peters

Code example please?

Thread Thread
 
pentacular profile image
pentacular
const add = a => b => a + b;
const eq = a => b => a === b;

eq(5)(add(2)(3));
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jwp profile image
John Peters

Just wondering how is that better than this?

const add(a,b)=>a+b;
add(2,3);

The decomposition of earlier example reveals a simpler understanding until one understands compositional parameter injection.

Thread Thread
 
pentacular profile image
pentacular

It's better if you want to use functions which have a uniform interface of transforming a single input value to a single output value.

Consider using map like so

[1, 2, 3].map(add(3))

Using the binary form of add you would need to introduce an ad hoc function to rectify the interface

[1, 2, 3.map(v => add(3, v))

The one to one mapping style generally makes composition simpler.

So, the question is, do you want to do that kind of stuff?

Collapse
 
iquardt profile image
Iven Marquardt • Edited

This is not partial application in its imperative meaning:

function sum(a) {
    return (b, c) => {
        return a * b * c
    }
}

sum(1);

It is a curried function that returns a multi-argument one.

Partial application is a dynamic concept of imperative programming. Here is a possible approach:

const partial = (f, ...args) => (...args_) =>
  f(...args, ...args_);

const sum = (a, b, c) =>
  a * b * c;

partial(sum, 1) (2, 3); // 6
Collapse
 
macsikora profile image
Pragmatic Maciej

How partial application have any imperative meaning? Partial application is just possibility of applying to function less arguments than function defines. If function is curried then partial application is just using this function property.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Note that real curry should return functions until all arguments are added. This is curry function I use in my code:

    function curry(fn, ...init_args) {
        var len = fn.length;
        return function() {
            var args = init_args.slice();
            function call(...more_args) {
                args = args.concat(more_args);
                if (args.length >= len) {
                    return fn.apply(this, args);
                } else {
                    return call;
                }
            }
            return call.apply(this, arguments);
        };
    }
Enter fullscreen mode Exit fullscreen mode

But also this function is modification of real concept of curry that return single argument functions only. Here you can use multiple arguments at once (which is much better).

You can test the curry function at: codepen.io/jcubic/pen/LxrOYP the code in demo use ES5.

Collapse
 
starboysharma profile image
Pankaj Sharma

Hey @Suprabha, thank you for this article. I just want to know in real-world why we need currying and where I should use currying. 🤔 As a developer, I would like to know the kind of problems you solve with currying.🤓🧐

Again Thank you...

Collapse
 
functional_js profile image
Functional Javascript

I make heavy use of currying with functional pipelines.

Here's an example of comparing a function pipeline with method chaining from a recent tweet.

Alt Text

src

twitter.com/Reactivizer/status/127...

the filterNotStartsWith and replaceByRegex funcs are curried (they are funcs that return funcs)

Here are their implementations....

/**
@func
from the supplied arr,
- remove the elems that don't start with the supplied str

@param {string} chunk
@return {(a: string[]) => string[]}
*/
export const filterStartsWith = chunk => a => fil(s => s.startsWith(chunk), a);


/**
@func
replace a substring with another substring in a haystack of text

@param {RegExp} n needleRegex
@param {string} r replacement
@return {(h: string) => string} - haystack
*/
export const replaceByRegex = (n, r) => h => h.replace(n, r);

Notice that if a func takes exactly one arg, I don't have to curry it in order to use it in a functional pipeline.

Finally, the functional pipeline can be executed like this...

functionalPipeline(`
pwd
git status
git stash --include-untracked
git pull
git stash pop
`);
Collapse
 
pentacular profile image
pentacular

You know that you can just write like this, right? :)

const sum = a => b => c => a + b + c;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joela11y profile image
joel-a11y

And that's a perfect example of currying, imho. Without any funky bindings :D

Collapse
 
safinghoghabori profile image
Safin Ghoghabori • Edited

I have one question please answer it and clear my dillema:

//below is currying function
const sum = a => {
return (b) => {
return a+b;
}
}

So my query is why we need to nest functions and make it currying? Why cant we simply define it as follow:

const sum = (a,b) => a+b;

In this way, we also pass a & b, whereas in first example we also pass a & b, then what is difference? What are advantages?

I didnt see anything about this, elaborate on this would be appreciated.

Thanks in advance!

Collapse
 
harshjoeyit profile image
Harshit Gangwar

Currying is also possible using .bind()

Collapse
 
joela11y profile image
joel-a11y

Hi guys!

I've been looking for a nice currying example and noticed few mistakes here. Just a few notes: sum(a,b,c) function provided last is not a best example of currying because currying is "single parameter at the time" (definitely not an add(20,90) etc), so sum(a,b,c) here is, probably, a good example of partial application. imho

Here are few interesting things described on wiki:
Wiki definition of curying: In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument;
and partial application definition: In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity

p.s. this is just my imho :)

Collapse
 
suprabhasupi profile image
Suprabha

I found the great article which might help for understanding between currying and partial application:
2ality.com/2011/09/currying-vs-par...

Collapse
 
chinmayghule profile image
Chinmay Ghule

The last part "To develop a function that takes a function and returns a curried function" was very confusing. What exactly happened there?