

Currying in JavaScript - kevincennis
https://medium.com/@kevincennis/currying-in-javascript-c66080543528

======
ufo
I didn't have a great experience with currying in Javascript when I tried to
use it. In Haskell passing the wrong number of arguments to a function results
in an immediate type error even when currying while in Javascript the error is
going to end up being shallowed by the currying. You will only notice the
problem a lot later, when you notice that something is a partially evaluated
function when it shouldn't.

Another problem with currying in Javascript is that it leads to more
complicated stack traces, which is unfortunate for debugging.

~~~
jfarmer
I might be misunderstanding your point about arity-related errors, but _every_
function in JavaScript is variadic, i.e., you can pass any number of arguments
to any function and JavaScript will happily call it. Excess arguments vanish
into the aether and un-supplied arguments arrive with a value of "undefined".
So, to the extent that what you describe is a problem, it's a problem baked
into the foundation of the language. :D

The OP is already using Function.length ([https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Refe...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)), so I
suppose one could roll their own arity-checking. It'd be a little out of sync
with the rest of the language, though.

~~~
antimagic
Obviously the solution as proposed only allows for non-variadic functions to
be curried (where 'non-variadic' means that the function needs to be called
with a fixed number of arguments to work correctly, not that it can't be
called with the wrong number of arguments, because clearly Javascript doesn't
care).

Does currying even make sense for variadic functions? I can't imagine what
that would look like as an implementation.

~~~
ufo
Its possible to curry a variadic function if there is a way to know when you
reached the last argument. For example, in a printf-like function you know the
number of inputs once you parse the format string.

This example here is a function that sums a variadic list of non-zero numbers.
The zero signals the end of the list.

[http://pastebin.com/xQRbRcJe](http://pastebin.com/xQRbRcJe)

Its certainly very weird though. I wouldn't recommend doing this in real
programs.

------
tel
Currying on the fly always feels a little silly to me. What's natural is just
defining functions in curried form from the get-go.

    
    
        function reduce(nil, cons) {
          return (ary) => {
            ...
          }
        }

------
tobyhinloopen
For every use case this might be applied, .bind -a built-in function- is
superior.

~~~
josteink
I actually had to look this up, because I didn't know about it, and yes I
agree.

MDN documentation contains some very illustrative examples of its use:

[https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Refe...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)

------
jamesfe
I guess I'd be more interested in how this solution came to be, rather than a
step by step of how to get there. What other methods did you try? What worked
and what didn't? How did you solve the problems you came across?

That being said - well written, very informative, and I very much appreciated
the simple and concise definition of currying.

Thanks.

~~~
kevincennis
Hey. Thanks so much for the feedback.

It's been a while since the first time I ever tried to do this, so it's a bit
difficult to remember exactly what my initial approach was. But I definitely
remember the moment where I realized I needed the `resolver` function.
Initially, I think I tried to just make `curry` return something that looked
like the anonymous function inside of `resolver` – which of course didn't
work, because I had no way to store all of the previous arguments.

Ultimately, I think there are probably a number of good ways to do this, and I
would never claim that mine is the "right" one. It's really just a
representation of the way I think about things, I guess.

If you do a bit of digging, there are some other great blog posts about
currying, and each one has a different approach. It's actually pretty
interesting to see how different people have implemented it. For a what
basically amounts to a 10-line function, there's a pretty amazing amount of
diversity in the way people approach it.

------
serve_yay
ES6 rest/spread operator is really nice for dealing with function arguments.

    
    
        function curry(fn) {
          return function accum(...args) {
             if(args.length >= fn.length) {
               return fn.apply(null, args)
             }
        
             return accum.bind(null, ...args)
          }
        }

------
tomkwok
A real-world use case of currying in JavaScript: jqMath [1] from
mathscribe.com, a lightweight alternative to jsMath (which is succeeded by
MathJax). jqMath utilizes its own jsCurry library [2], and both are released
under MIT license.

[1]:

[http://www.mathscribe.com/author/jqmath.html](http://www.mathscribe.com/author/jqmath.html)

[http://www.mathscribe.com/mathscribe/jqmath-0.4.3.js](http://www.mathscribe.com/mathscribe/jqmath-0.4.3.js)

[2]:

[http://www.mathscribe.com/mathscribe/jscurry-0.4.0.js](http://www.mathscribe.com/mathscribe/jscurry-0.4.0.js)

[http://www.mathscribe.com/mathscribe/jscurry-
documentation.t...](http://www.mathscribe.com/mathscribe/jscurry-
documentation.txt)

~~~
cturhan
Thanks! I was looking For possible use cases 😊

------
ufmace
It's a neat solution and a good demo of the cool stuff you can do with
Javascript. I kinda doubt the practicality, though. If I wanted to do
something like that in production, I think I'd rather just define a new
function right there, since you could curry any argument order you wanted
instead of only in order, and you could name everything more clearly and have
the code that you're running right there instead of in a far-away library.

Like if you had to call a method like this:

sendMessage(sender, receiver, data);

a bunch of times with the same receiver but different senders, you could
define:

function sendMessageToBob(sender, data) { sendMessage(sender, bob, data); }

------
couchand
_We can tell how many arguments a function expects by accessing its length
property._

While that works for many cases it isn't generally true. For instance:

    
    
        function wtf() { return arguments[0]; }
    

While that may seem like a ridiculous example, the following idiom is quite
common in JS programming:

    
    
        function accessor(value) {
            if (typeof value === 'undefined') {
                return getValue();
            }
            else {
                setValue(value):
            }
        }
    

In general it's not a good idea to expect any particular value for a
function's length property.

~~~
kevincennis
Right, but you wouldn't curry those functions.

------
citizenofpluto
clicked on the link hoping it would explain why I might need to use currying.

~~~
braythwayt
It’s often the case that writing a bit of infrastructure for something is a
valuable exercise in and of itself.

So we can debate how often you’d need to curry a function, but I feel safe
suggesting that writing your own curry function (or reading along with an
essay that does the same with lively interest) is valuable.

Same with things like classes and mixins, there is now syntactic sugar for
such things, but it’s always a good thing to have written your own MakeClass
function at least once.

~~~
kevincennis
OP here.

That was kind of my intent (learning exercise rather than super practical
real-world technique) -- but I'll admit I probably could have picked a better
title.

~~~
braythwayt
Well, I liked it, and I personally don’t mind the title. It’s about currying
and JavaScript, and it’s interesting, so that meets my (possibly low) bar for
upboating.

------
graememcc
For those wanting to explore more, my library, funkierJS
([http://www.graememcc.co.uk/funkierJS](http://www.graememcc.co.uk/funkierJS),
introductory blog post
[http://www.graememcc.co.uk/2015/06/07/onfunkier/](http://www.graememcc.co.uk/2015/06/07/onfunkier/))
has built-in currying, and provides curried implementations of most ES5 built-
in functions.

------
twic
Why does this need the immediately invoked function called 'resolver'?
Immediately invoked functions are usually about establishing a clean
namespace, aren't they? What's this one being used for here?

Also (possibly related), what does 'arguments' in "Array.prototype.slice.call(
arguments )" resolve to, and when? I would have thought it would be evaluated
when 'resolver' in invoked, and would therefore evaluate to an empty array. If
so, isn't there a simpler way to make an empty array?

~~~
kevincennis
Both good questions.

The immediately invoked function is really just a slightly less verbose way to
do this:

    
    
        function resolver() {
    
        }
    
        return resolver();
    

The reason that I gave it a name instead of using an anonymous function (as is
common with immediately invoked function expressions) is because I need to be
able to call it from within itself. This function is all about creating a
closure where we can store all of the arguments we've received so far.

As for your second point: The _first_ time that `resolver` is called,
arguments is in fact empty. But if you read a bit further, you'll see that
`resolver` calls itself recursively (indirectly, via the anonymous function it
returns), and does in fact pass arguments. So you can't just start off with an
empty array each time. You need to make sure you're taking into account any
arguments that were passed in. Does that make sense?

------
cturhan
Although I like currying a method, I think it makes things difficult. Think
about it, you joined an ongoing project and see curried functions and
variables around. You have to check each function if it's curried from another
to find original function (in this case `volume` function) and that might be
exhausting. Without proper documentation for every curried function, it might
be time consuming.

------
luckydata
Why is this useful?

~~~
wizao
[https://www.youtube.com/watch?v=m3svKOdZijA](https://www.youtube.com/watch?v=m3svKOdZijA)

------
taylodl
Memoization is a good use case for currying which I blogged about -
[https://taylodl.wordpress.com/2013/11/05/functional-
javascri...](https://taylodl.wordpress.com/2013/11/05/functional-javascript-
currying/)

------
exa
Nice. I wrote an es6 version.
[https://gist.github.com/edge/af86d57fcadd21f9e587](https://gist.github.com/edge/af86d57fcadd21f9e587)

------
amelius
In my opinion, this functionality should be part of the new javascript
standard.

~~~
kevincennis
You can get a lot of value out of `Function#bind()`, which has been around
since ES5.

That doesn't let you curry functions, but it does give you partial
application, which I think is actually more useful on a day-to-day basis. If
you're not familiar, here's a very quick and admittedly somewhat contrived
example:

    
    
        function clamp( lo, hi, val ) {
          return Math.max( lo, Math.min( hi, val ) );
        }
    
        var tenToTwenty = clamp.bind( null, 10, 20 );
    
        tenToTwenty( 5 );  // 10
        tenToTwenty( 15 ); // 15
        tenToTwenty( 25 ); // 20
    

For what it's worth though, I agree that having Function#curry in the ES spec
would be pretty cool.

~~~
hajile
You shouldn't use bind() for two very good reasons. First, it's performance is
abysmal. Second, if you .bind(foo) a function and .call(bar) on it later, it
silently ignores the new 'this' argument.

~~~
juliangregorian
Hyperbole much? Those aren't "very good reasons" to avoid an entire, useful
language feature! I would like to know how exactly you find it's performance
to be "abysmal" as I have used it in very high volume streaming code with no
problems. The second "problem" is perhaps surprising to a newbie but is not
hard to debug.

~~~
jondubois
I haven't witnessed 'abysmal' performance either. Based on some tests I just
ran, calling a bound function is only about 25% slower than calling a non-
bound one. That's pretty reasonable. Calling bind() on a function doesn't
appear to take that much CPU time either.

That said I don't see the applications for currying in JavaScript. It just
makes code less readable. It looks like an anti-pattern to me.

~~~
hajile
Are you sure about those numbers (can you show your code?) Every benchmark
I've seen shows a much bigger difference. Here's a jsperf (courtesy of the
WayBackMachine) that shows a difference of about 20x+ over normal function
calls.

[https://web.archive.org/web/20141121220218/http://jsperf.com...](https://web.archive.org/web/20141121220218/http://jsperf.com/function-
calls-direct-vs-apply-vs-call-vs-bind/33)

------
ternaryoperator
Additional info on currying (and partial functions) in JS from Dr. Dobb's[1]

[1] [http://www.drdobbs.com/231001821](http://www.drdobbs.com/231001821)

------
jdd
For those interested lodash provides _.curry and _.curryRight methods with
placeholder support as well.

See [https://lodash.com/docs#curry](https://lodash.com/docs#curry).

------
edem
What does Project Decibel do?

