Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active February 14, 2017 14:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/8de7ababf2107508334b9328e5d5a190 to your computer and use it in GitHub Desktop.
Save klmr/8de7ababf2107508334b9328e5d5a190 to your computer and use it in GitHub Desktop.
Currying explained

In the following, let’s define sum as

sum = function (a, b, c) a + b +c

Because base::sum’s definition involves ..., which would make the following explanation unnecessarily complex.


Partial function application takes a function f with n formal parameters and m=1…n arguments, and fixes some of f formal parameters by filling them in, thereby reducing f’s arity to nm.

f = partial(sum, 1)
f()
f(2, 3)
## 1
## 6

Currying takes a function f with n formal parameters and produces a recursive nesting of n functions, each taking 1 formal parameter. Recursively calling all these functions is then identical to calling the original function:

g = curry(sum)
g()
g(1)(2)(3)
0
6

Conversely, uncurry reverses a currying:

foo = function (a)
    function (b)
        function (c)
            a + b + c

foo(1)(2)(3)

bar = uncurry(foo)
bar(1, 2, 3)
## 6
## 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment