Skip to content

Instantly share code, notes, and snippets.

@ficapy
Created February 24, 2021 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/6b8516b738f713336c973d58ac779e3b to your computer and use it in GitHub Desktop.
Save ficapy/6b8516b738f713336c973d58ac779e3b to your computer and use it in GitHub Desktop.
// https://hackernoon.com/currying-in-js-d9ddc64f162e
function curry1(fn) {
function nest(N, args) {
return (...xs) => {
if (N - xs.length === 0) {
return fn(...args, ...xs);
}
return nest(N - xs.length, [...args, ...xs]);
};
}
return nest(fn.length, []);
}
function curry2(fn) {
return (...xs) => {
if (xs.length >= fn.length) {
return fn(...xs);
}
return curry2(fn.bind(null, ...xs));
};
}
function curry3(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function (...args2) {
return curried.apply(this, args.concat(args2));
}
}
};
}
const sum3 = curry2((x, y, z) => x + y + z);
console.log(sum3(1, 2, 3), sum3(1, 2)(3), sum3(1)(2, 3), sum3(1)(2)(3),); // 6 6 6 6
def curry1(fn):
def nest(n, *args):
def inner(*xs):
if (n - len(xs) == 0):
return fn(*args, *xs)
return nest(n - len(xs), *[i for i in args + xs])
return inner
return nest(fn.__code__.co_argcount, *[])
def curry2(fn):
def curry2_(fn, n):
from functools import partial
def inner(*xs):
if len(xs) >= n:
return fn(*xs)
return curry2_(partial(fn, *xs), n - len(xs))
return inner
return curry2_(fn, fn.__code__.co_argcount)
def curry3(fn):
from functools import partial
def curried(*args):
if len(args) >= fn.__code__.co_argcount:
return partial(fn, *args)()
return lambda *args2: partial(curried, *[i for i in args + args2])()
return curried
def sum(x, y, z):
return x + y + z
s = curry3(sum)
print(s(1)(2)(3))
print(s(1)(2, 3))
print(s(1, 2)(3))
print(s(1, 2, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment