Having a function f that takes arguments x1, x2, …, xn
– ie. f : X1 × X2 × … × Xn → Y
– currying redefines f as a function taking a single argument a1 which maps to yet another function. This technique is useful for partial application, for example with a curried pow
function we could write exp = pow(e)
.
Example
Assuming we have the following function f taking three arguments (f : X1 × X2 × X3 → Y):
def f(a,b,c):
return a + b * c
Currying this function leaves us with f_curry: X1 → (X2 → (X3 → Y)), if we would now call that function twice with f_curry(1)(2)
we would get a function (h
) equivalent to the following returned:
def h(c):
return 1 + 2 * c
The curried function f
could be written like this (Python 3):
def f_curry(a):
def g_curry(b):
def h(c):
return a + b * c
return h
return g_curry
Challenge
Your challenge will be to curry a function as described above, here are the rules:
- Input will be a blackbox function which takes at least 2 arguments
- The input function will always have a fixed number of arguments (unlike
printf
or similar, note: you need to support functions with any number of arguments ≥2) - If your language uses curried functions by default (eg. Haskell), you may expect the input function to be defined over N-tuples, instead of a "higher-order function"
- You may take the number of arguments as input
- Output will be the input's curried equivalent*
- You may assume that the output function will only ever be:
- called with less or equal to the number of arguments that the input function takes
- called with arguments of the right type
* This would mean for an input f
with N
arguments and an output h
that for all valid arguments a1,…,aN
it holds that f(a1,a2,…,aN) == h(a1)(a2)…(aN)
.
def f(a,b,c): return a + b * c
and the output isdef f_curry(a): def g_curry(b): def h(c): return a + b * c return h return g_curry
? \$\endgroup\$f
(which is defined somewhere) and the output should be something equivalent tof_curry
. Or the input would belambda a,b,c: a+b*c
and the output a function equivalent tof_curry
. \$\endgroup\$