70 comments

[ 4.2 ms ] story [ 160 ms ] thread
I favour a nice hot Rogan Josh. Helps me write excellent code the next morning. Not so the half a dozen pints I had along with it.
Currying is the process of turning a function that expects multiple parameters into one that, when supplied fewer parameters, returns a new function that awaits the remaining ones.

I think this, along with the whole article, is the best explanation of currying I've seen on the whole damn internet.

It's also wrong :)

http://www.uncarved.com/blog/not_currying.mrk

Which the author freely admits:

(Some will insist that what we're doing is more properly called "partial application", and that "currying" should be reserved for the cases where the resulting functions take one parameter, each resolving to a separate new function until all the required parameters have been supplied. They can please feel free to keep on insisting.)

Yes, freely admitted. (Author here.)

I feel that although the distinction can be very important, it's much less so for Javascript. And the implementation in Ramda can be used that way any time you choose:

    var total = reduce(add)(0);  // or 
    var sum = reduce(add)(0)(numbers)

works just as well in Ramda as

    var total = reduce(add, 0);  // or
    var sum = reduce(add, 0, numbers)
So, as I said, feel free to keep on insisting. :-)
http://vimeo.com/96639840

Start at 26mins. You don't have flip. You lose control over partial application. It isn't curry. You're right. It is an important distinction :)

This implementation of multi-argument partial application does not in any say prevent implementation of flip. It's just syntax sugar.
I finally got a chance to watch that video, and it looks as though what you're worried about is `flip`. Ramda for one already includes a version that works much like Haskell's. I don't know if this satisfies your objection, though.
As I stated above... flip is well defined so long as your arguments are positional.
As long as you have ordered parameters, I'm not sure this is such a big issue. First, tuples are (morally, i.e. up to non-termination) associative in most reasonable languages, so the product/exponential adjunction can be shifted around however you like

    -- all morally identical
    a ->  b -> c   -> d
    a -> (b -> c   -> d)
    a -> (b -> (c -> d))
    (a, b)  -> c   -> d
    (a, b, c)      -> d
    ((a, b), c)    -> d
    (a, (b, c))    -> d
However, so long as you have parameter order (we're not allowed to commute our tuples, just reassociate nested tuples like ((a, b), c) <-> (a, (b, c)) and so on) then flip still morally works

    flip (someFn :: (a, b, c) -> d)
      :: (b, a, c) -> d
      :: (b, a) -> c -> d
      :: b -> a -> (c -> d)
The same story holds for partial evaluation. Of course, there have to be far more edge cases to handle all this tuple twiddling.

---

Really, I think it's pretty meaningful to blur the distinction between "curry (once)" and "curry repeatedly along with tuple reassociation". The later forms an equivalence class of function types which all have the same application behavior.

Also to explain that strange "adjunction" comment, currying results from the notion that the things of type

    (a, b) -> c
are exactly equivalent to the things of type

    a -> (b -> c)
An adjunction (F, G) occurs when the things of type (F a -> c) are equivalent to things of type (a -> G c), so if we pick F x = (x, b) and G x = (b -> x) then we see that currying is an adjunction between (,b) and (b ->).
One intuition for this is that (a, b) is the product type (a × b) and the function arrow (a → b) corresponds to exponentiation (b^a), so you get the isomorphism for free from the identity c^(a × b) = (c^b)^a.
Currying can be hard to spot if you're not used to it. Especially in a language with inferred or dynamic type, it's not obvious that the var contains a function, not a result object.

var result = somefunc(a,b) // object var otherResult = somefunc(a) // function

It gets even more confusing if overloading of function names for different parameters or different number of parameters is allowed.

So elegant: maybe. Readable: no. Depends on the programming language.

I second that. Just adding unnecessary complexity to save on a few lines of code that are so common most people don't even spend mental effort processing them.

Basically, it seems to me like trying to fix something that isn't broken.

Don't know about how it's used for dynamic languages (it might be that it makes them harder to understand), but in languages with static typing, the purpose is not to save a few lines of code.

The purpose of currying is to improve reuse and chaining of functions, resulting in easier to read and more elegant code.

And this works as long as everyone is fully committed to functional programming and you have little to no turn over or a small dedicated team.

The minute you step into the standard industry things change a little bit. I once maintained an amazing piece of javascript that did dynamic server requests and rendered graph data, processed user input, changed views, and make lasting configuration changes to the database. The first 30 or so lines of code was simply setting up the functional haskellish environment for javascript, and the last 40 lines + 40 lines of HTML put everything else together. It was terse, compact, elegant, and impossible to maintain or make wider changes after the original author had moved on. It was tightly contained into one piece of the code, so not something that will be seen on the mainline easily. Going in and fixing any tiny little bug forced any unfortunate developer to immediately learn Chinese. Someone was tasked to re-write it so the rest of the team could maintain it effectively.

I like ruby/python a lot because it meets in the middle fairly easily, and doesn't require contortions to the natural intent of the language to get rid of cruft.

Please note I specifically said I wasn't talking about javascript or languages with dynamic typing in general. I'm not fluent in javascript and the only js code I've looked at in my current job is HORRIBLE, and it isn't functional-style code. We are phasing it out because no-one wants to touch it.

I was talking about currying and FP in nicer languages.

And that's fine. The concept of functional programming (currying, etc) is still difficult to execute on a large team or in a long-running code base with developer turn over. That said, new programmers are born everyday and they are finding themselves in a world we didn't. A lot of kids these days love python so they get introduced to list comprehensions quickly. C++ or Java never gave you that right away.
What isn't difficult to execute on a large team or in a long-running base with developer turn over?
Who said it wouldn't be difficult?
I don't think currying can reasonably be combined with optional parameters. At least I've never seen a useful way to do so.

In a previous article (http://fr.umio.us/why-ramda/) I discuss more thoroughly how I would tend to use this currying, namely to build up collections of useful functions, often in points-free style, so that major parts of the application would end up as (ideally well-named) functions, each which serve as pipelines of these smaller functions, passing data through the system.

I do find this significantly more readable, but _de gustibus non est disputandum_.

I've never used that particular feature, but Livescript lets you use default arguments on curried functions by calling with no arguments.

http://livescript.net/#functions

Which implies there's a distinction between "siphoning arguments around" and "application". That feels very weird.
If I'm writing a function where there isn't an obvious order for the arguments, I chose the order such that Currying is most useful, even if the language I'm writing in doesn't support Curried functions/partial function application. You never know when someone will port your code or create cross-language bindings.

For instance, my company writes a lot of code in a proprietary language and the other day I was writing a function to generate random strings, given a length and an "alphabet" string from which to choose characters.

I chose the ordering:

    randomString alphabet length = ...
so that if partial function application were added to the language, one could simply write the functions randomHex and randomBase32 as:

    randomHex = randomString "0123456789ABCDEF"
    randomBase32 = randomString "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
The alternative ordering would allow me to easily write functions that generate fixed length strings and take their alphabets as inputs:

    random10Char = randomString 10
    random4Char = randomString 4
This ordering is much less useful in general, so I chose to make the alphabet the first parameter.

On a side note, our language also has some time series extensions for dataflow programming. There's an API for efficiently adding new data flows based on something similar to template specialization, but the API is unwieldy and the source of much confusion. So, I wrote a wrapper API that uses reflection to expose the same functionality as partial function application / Curried functions over time series.

I've done that too, then had to wave my hands about why I choose that parameter order, when I know damn well the languages isn't going to change... "But just in case...." :-)
It's an interesting design question to pick orderings that work best with currying.

Oddly though, when writing haskell code, I don't worry about it much. Once I find myself needing to `flip` a function before using it, I have determined experimentally that the original parameter order I picked was not the best one, and I then go change the function, and let the type checker walk me through fixing any necessary call sites (which also verifies if the new parameter order is better or not).

Depending on the size of your codebase, and the human and financial costs of a mistake, code reviewers may need strong justifications for function signature changes. Also, in my case, the language is gradually typed, so the type checker helps a lot, but doesn't disprove the possibility of runtime type errors.
I wonder why languages don't support currying arbitrary parameters.

It seems like it would be easy enough to have a special "placeholder" keyword that means "these parameters will be the parameters of the curried function". To take his example:

    var jp = formatNames2('John', 'Paul');
That might be written like this instead:

    var jp = formatNames2('John', 'Paul', _);
And then if you want to curry the second parameter instead of the third, it's easy:

    var jp = formatNames2('John', _, 'Jones');
Or maybe they do and I just haven't heard of it?
Well, C++ has it. It is called std::placeholders::_1, std::placeholders::_2, ...
Clojure[0] and Anarki[1] (public fork of Arc) both provide a way to do this (with more than one argument as well). They both have syntax for a "literal function". Your second example would become:

Arc/Anarki: [format-names2 "John" _ "Jones"] which expands to (fn (_) (format-names2 "John" _ "Jones"))

Clojure: #(format-names2 "John" % "Jones") which expands to (fn (%) (format names2 "John" % "Jones"))

Then for a function of two arguments that curried the middle one:

Anarki: [format-names2 _1 "Paul" _2] which expands to (fn (_1 _2) (format-names2 _1 "Paul" _2))

Clojure: #(format-names2 %1 "Paul" %2) which expands to (fn [%1 %2] (format-names2 %1 "Paul" %2))

[0] http://clojure.org/reader [1] https://github.com/arclanguage/anarki/blob/master/CHANGES/ma...

I should have known that if I can imagine a language feature, it will already be implemented in the Lisps....
I can think of both space/speed and syntactic reasons.

The better argument is from syntax. You can think of partial function application as shorthand for lambdas.

    someFunc A B C = ...
    myFunc = someFunc "earlyParam"
is shorthand for

    someFunc A B C = ...
    myFunc = \B C -> someFunc "earlyParam" B C
Now, what syntax would you use for arbitrary order partial function application that's both elegant and more terse than just writing the lambda? (Also, if a compiler performs inlining to optimize partial function application, it's just as easy to perform the same optimizations for lambdas when the same information is available at compile time.)

The space and time performance argument is weaker:

If you have a language that compiles to native code, your calling convention passes everything on the stack (parameters on the right first), all parameters are the same size (as is the case for OCaml and other languages that pass everything as either a small integer or a pointer to a boxed value) and you only allow partial function application starting at the left parameter, then the partial function application native stubs for partially applying up to 10 parameters only requires 10 stubs. It's easy to include these stubs in your standard runtime, and the performance is very good. If the calling convention requires the callee to clean up the stack (Pascal/Windows Syscall calling convention), then the stubs don't even need to modify the return address, just copy the return address N words up the stack and copy in the partially applied parameters and then jump to the original function entry point.

On the other hand, if you allow arbitrary Currying order, then the number of stubs explodes combinatorially and you're going to have to generate each stub in the compilation unit that needs it, maybe with a few common stubs in the standard runtime library.

Of course, calling conventions with different parameter sizes and passing some parameters in registers complicates things, but you still wind up with a much simpler situation if you only allow partial application starting at one end of the parameter list.

The syntax argument is more compelling.

Firstly, this is definitely partial application not currying (see my other post on this thread for great expansion on this point).

Secondly, this is merely a syntactic item you're looking for. It's trivial to achieve this end in any language with first class anonymous functions. I'm not claiming that syntax isn't important, but instead just pointing out that it really is a trivial transformation to include if it were valuable enough.

I have a Python function that allows both of those:

    def randomString(alphabet, length):
        ....

    randomHex = partialApply(randomString, alphabet="0123456789ABCDEF")
    randomBase32 = partialApply(randomString, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
    random10Char = partialApply(randomString, length=10)
    random4Char = partialApply(randomString, length=4)
    randomHexByte = partialApply(randomString, "0123456789ABCDEF", 2)
Comes in handy occasionally.
And in case anyone else wants such a function, it's available in the standard library as functools.partial: https://docs.python.org/2/library/functools.html
Eh, I don't like the one in functools. It allows overriding of variables previously defined, which personally causes more problems than it solves.

(So `functools.partial(foo, b=3)(a=1, b=2)` doesn't throw an error, and is equivalent to calling `foo(a=1, b=2)`)

I think languages that have named parameters have very different sorts of techniques for these things. I don't know if they're more powerful or not, but they take a very different approach, and offer different design choices.
Upvoted just for the quality of the pun.
Have to thank/blame @buzzdecafe for that!
Is the final code equivalent to:

  var getIncompleteTaskSummaries = function(membername) {
    return fetchData().then(function(data) {
      var incompleteTasks = [];
      for (i = 0; i < data.tasks.length; ++i) {
        var task = data.tasks[i];
        if (task.username == membername && !task.complete) {
          incompleteTasks.push({id: task.id, dueDate: task.dueDate, title: task.title, priority: task.priority});
        }
      }
      incompleteTasks.sort(function(a, b) {
        return a.getTime() - b.getTime();
      });
      return incompleteTasks;
    });
  }
?

Apologies if that's wrong, i barely know JavaScript.

That code is not so great, and a bit '90s, but it's not appalling. The horrifically verbose non-currying code in the article isn't something i see any need to write. It looks like an outrageous strawman to me.

My code here could definitely improved with some functional idioms for the looping, picking, and sorting, but i wouldn't reach for currying here.

Yes, at first glance, that's pretty close. (You'd have to do something about `.getTime()`, as the original just did lexicographic sorting on date strings.)

The article really didn't get into the fact that these blocks of code that were listed inline would ideally represent reusable functions. That these functions would best be defined separately and only included by reference would have cluttered the article, but leaving them out does make it feel a bit like a strawman, I agree.

The breakdown of a task into these smaller functions is something I discussed more fully in the previous article: http://fr.umio.us/why-ramda/

This is perfectly good style, and better than the original article. Don't listen to the functional language fans. Replacing the for loop with its functional equivalents would make it less readable.
Currying with map/reduce/filter can be hard to read, but list comprehensions are pretty nice:

   (defn get-imcomplete-task-summaries [membername]
      (.then (fetch-data)
             (fn [data]
               (sort-by :time
                        (for [task (:tasks data)
                              :when (= membername (:username task))
                              :when (not (:complete task))]
                          task ;; immutable, no need to copy
                          )))))
It makes me a little sad that functional programming has come to mean map/reduce/filter for lots of people, rather than avoiding mutation which is far more interesting.
Well, avoiding mutation can be helpful but it's not a rule to be followed blindly either. A mutable local variable never hurt anyone, so long as it doesn't leak out of the function.
Even in a multiple-thread scenario?
If it doesn't leak out of the function (though a closure or a pointer), how can another thread see it? It's only on one stack.
As an aside, one of the really interesting ideas that's bubbling up from Rust is that it's not mutable state that's a problem, it's shared mutable state, and that you can make it safe by removing the sharing, rather than removing the mutability:

http://smallcultfollowing.com/babysteps/blog/2014/05/13/focu...

I have no idea if this is true, but it's going to be really interesting to see that idea tried.

Just to note, the copy wasn't meant to deal with mutability but to note a changed interface. The items that are emitted have only a subset of the properties of those ingested. We could as easily have added some new properties to them as well. Mutability wasn't the primary concern here (although in Javascript it's always a genuine concern.)
Replacing the for loop with its functional equivalents would make it less readable.

Readability is in the eye of the beholder. A tidy functional equivalent might look something like this (in a made-up syntax with typical functional idioms):

    getIncompleteTaskSummaries membername =
        fetchData
        >>> tasks
        >>> filter (task => username task == membername and not complete task)
        >>> map (subsetkeys ["id", "dueDate", "title", "priority"])
        >>> sortwithkeyfn getTime
Compare that with the explicit loops and tests above:

    var getIncompleteTaskSummaries = function(membername) {
        return fetchData().then(function(data) {
          var incompleteTasks = [];
          for (i = 0; i < data.tasks.length; ++i) {
            var task = data.tasks[i];
            if (task.username == membername && !task.complete) {
              incompleteTasks.push({id: task.id, dueDate: task.dueDate, title: task.title, priority: task.priority});
            }
          }
          incompleteTasks.sort(function(a, b) {
            return a.getTime() - b.getTime();
          });
          return incompleteTasks;
        });
      }
In practice, functions like filter, map, subsetkeys and sortwithkeyfn would probably be in your standard library and immediately familiar to anyone used to programming in such a language, so the only interesting details are the interesting details: which tasks you want to pick out, how you want to summarise them, and how you want the results ordered. Depending on what else is going on, you might even extract some or all of those three details into named one-liner functions to make the main algorithm more self-documenting and/or to allow those concepts to be reused elsewhere.

The functional version as shown reduces 10 substantial lines with a lot of temporary variables and deep nesting to 6 total lines that each have a clear, self-contained purpose and that collectively systematically transform your input to your output. To my eyes, that style is far more readable and maintainable than manually reinventing fundamental algorithms like filter and map and camouflaging the interesting details within three or four levels of context.

Edited to add: Often the thing that makes functional style awkward is when a language that wasn’t designed with that style in mind adopts some of the useful concepts but without the elegant syntax and idioms to match. For example, we have somewhat unwieldy notation for defining quick local functions in JavaScript, lambdas that work as long as you can do everything on one line in Python, and the horrific lambda expression notation in modern C++. But I don’t think it’s helpful to conflate this with functional programming style itself, any more than it’s helpful to conflate Java’s verbosity with static type systems.

Well, I could convert it to a SQL statement too, but then we're no longer using a general-purpose language. Filter, map, and so on are additions to the basic for loop that everyone already needs to know how to use.

"you might even extract some or all of those three details into named one-liner functions"

No. Replacing familiar operations with unfamiliar ones (adding a level of indirection) doesn't add readability or make it "more self-documenting" than pure boilerplate code that everyone's seen many times before and will see again.

But these sort of arguments never reach a conclusion. The way to test it would be to teach beginners and see which one is easier to teach. That's a bit beyond a casual internet discussion, though. :-)

I see this assumption quite frequently -- That what is easy for a beginner is easy for an expert. I'm not sure that's the case.

FWIW, I'm in the anti-boilerplate camp.

Well, most things are easier for an expert, or they wouldn't be an expert, right? I think it's good practice to try to write code that's readable by people with a wide variety of skill levels.
I began programming in September of last year. For loops were trivially easy to understand (took me about a day), 1-2 weeks to become proficient. I started with php, moved to 'jquery', and then rails. Rails pisses me off. I said fuck this class I'm learning node/javascriot. After a week of js I switched to clojure (my instructor hadn't even heard of it, this is a full day bootcamp coding course). Rich Hickey is my single greatest influence in programming habits styles. I spent a few months, off and on, learning clojure. I still can't program competently, but I learned how to replace for loops with map / filter / reduce. Once I realized what was going on there, I had my greatest 'ah ha' moment in programming thus far. Clojure blogs led me to Om, om to react, react to frp and gulp, gulp lead to streams / piping, and I haven't used a for loop in 6 months. It's boilerplate that's so trivial, you only need to code for about 3 months for the functional abstractions to become more useful to you. It took me a few weeks to learn how map, filter, reduce work. It took me a few hours to learn a 4 loop. I still consider myself am amateur programmer, but this trend of code abstraction will continue rapidly, and our CPUs and more that capable of handling the potential performance hits.
"Ok, here we go. Does code like this look at all familiar?"

No, because I use Array.prototype.filter(), Array.prototype.map(), and Array.prototype.reduce() to accomplish these things...

Yeah, I probably shouldn't have cribbed the example from my old "Intro to Functional Programming" talk...
Basic point free style as described in the article is alright in javascript.

Extreme point free style does not work in javascript, AT ALL!!!! Two reasons:

1) Find the bug: the table sort is glitchy. Is the bug in this suspicious line, or somewhere else? (Real line of code in a codebase I inherited, and yes there is a bug in it)

    var sorted = rows.sort(_.unsplat(_.pipeline(
        _.partial(_.map, _,  accessor), 
        _.splat(comparator))));
2) I use React, so I can get away with a lot of really functional stuff since React is well suited for functional javascript. React is a great functional abstraction, but under the abstraction is imperative code. Imperative code means you need a debugger. When you write in a point free style, there's nowhere to place a breakpoint!
It is harder to debug points-free code. I find myself doing more debugging with `log` statements in a long pipeline than I do with other styles of code.

On the other side, I tend to work with a few well-tested functions over and over and end up with fewer problems to debug when I work in a functional paradigm, points-free or not.

On rare occasions, when I need to debug something that is difficult because it's points-free I simply add some explicit parameters, either temporarily to enable debugging or permanently.

Points-free is nice, but should never be an overriding goal.

I'm generally a fan of currying, but specifically when used with javascript, I think it can be problematic. The default behaviour of any function when called with fewer arguments than specified is to set named arguments to undefined. Meaning, functions in javascript always take any number of arguments and changing that default behaviour is confusing. There is also the matter of the "this" parameter.

I think that using the .bind() method on functions is the right approach. It will lead to less surprising behaviour in the context of javascript.

Currying is the factory factory pattern for λ people.
I'm probably missing something, but why not just do...?

  var jp = function(last){
      return formatNames2('John', 'Paul', last);
  }
You can if you want:

    var jp = function(last) {
        return formatNames2('John', 'Paul', last);
    };
    var je = function(last) {
        return formatNames2('James', 'Earl', last);
    };
    var lh = function(last) {
        return formatNames2('Lee', 'Harvey', last);
    };
    var c = function(middle, last) {
        return formatNames('Clarabelle', middle, last);
    };
But I find this cleaner:

    var jp = formatNames2('John', 'Paul'};
    var je = formatNames2('James', 'Earl'};
    var lh = formatNames2('Lee', 'Harvey'};
    var c = formatNames('Clarabelle'};
Should you really have jp je lh and c at all than? Having so many different functions seems like a problem on its own, and maybe there should just be an array of names and a function iterating over them...
It's a toy example; he's just trying to show how currying works, rather than why you should use it.

If anything, it does show that one useful thing about partial application is that you can write a generic function (formatNames) and then make it more specific (formatNames("John")) without repeating yourself.

I think I understand how it works, I just haven't seen examples that demonstrate why it is useful.
Say you want to calculate distances from origin to each point in array, and keep only these greater than R.

Using fors and ifs:

    var origin = Point(0, 0);
    var R = 100;
    var result = [];
    for (var i : array) {
        tmp = distance(array[i], origin);
        if (tmp>R) {
           result.append(tmp);
        }
    }
Without currying (nobody would write it that way):

    var origin = Point(0, 0);
    var R = 100;
    result = filter( map(array, function (x) { return distance(x, origin); }),
                     function (x) { return greater(x, R);} );
With currying it almost reads like SQL:

    var origin = Point(0, 0);
    var R = 100;
    result = filter( map(array, distance(origin)), greater(R) );
It's useful for functions that you predict will be used many times with one of the arguments the same. Yes, it's just syntactic sugar, but it sometimes makes code clearer (especially when literal function syntax is as verbose as in javascript).
A nice example. Thank you.

I just want to note that in Ramda, because of it's strong insistence on a data-last API (which makes the currying easier), this would be written in this order:

    result = filter(greater(R), map(distance(origin), array));
But it's precisely the same idea.
I have no experience neither with JS nor with functional programming, but know Lambda calculus and currying from Discrete math courses.

As Currying and functional programming a popular thing now, I was thinking what my current codebase would look like in C# if I were writing code in a more functional way.

So, obviously C# isn't a functional languageat all but using Func<T>, and maybe some delegates would enable this easily.

I'm not sure this would turn my code to more elegant or readable.

What would I benefit from ?

I'm not really a C# person, but from what I know of the language, although it has some lambdas and some other functional features especially around LINQ, functional programming really is against the grain of the language, and would not be easy to integrate into the same code.

The .NET platform of course has F#, which is a dedicated functional language. Some day I'll spend some time learning this one... perhaps.

The "curried" code seems less readable and maintainable than the original code. Is this like dependency injection where I have to make my code harder to read and maintain to satisfy some technical definition of "loosely" couple?
It'll seem less readable at first, yes. I've seen a codebase transformed by currying. We were able to remove six functions from one webservice interaction service, and handfuls throughout other parts of the code, and have made debugging and maintenance easier.

The code is a little more confusing at first glance. The developers who replaced the code with curried functions didn't inform the whole team what they were doing. There were a lot of wtfs until they clarified. Now we can read it, and I know I'll be looking for places for partial applications.