-
-
Save zfogg/9d69011f501437217c6e to your computer and use it in GitHub Desktop.
Tools to partially apply functions with their arguments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# USAGE: | |
Math.pow.curry()(2)(5) # == 32 | |
Math.pow.curry()(2, 5) # == 32 | |
Math.pow.curry(2, 5) # == 32 | |
Math.pow.curry(2)(5) # == 32 | |
# It works with any number of args: | |
((a,b,c,d) -> [a,b,c,d]).curry(1)(2,3)(4) # == [1,2,3,4] | |
# curryFlip is like curry, but the args are applied in reverse. | |
Math.pow.curryFlip(5)(2) # == 32 | |
((a,b,c,d) -> [a,b,c,d]).curry(1)(2,3)(4) # == [4,3,2,1] | |
# And just for laughs: | |
Math.pow.curry()()()(2)()()()(5) # == 32 | |
# Function::curry | |
Fn = | |
partial: (f, args1...) -> (args2...) -> | |
f.apply @, args1.concat args2 | |
partial$: (f, args) -> | |
Fn.partial.apply @, [f].concat args | |
flip: (f, args1...) -> (args2...) -> | |
f.apply @, (args1.concat args2).reverse() | |
flip$: (f, args) -> | |
Fn.flip.apply @, [f].concat args | |
curry: (n, f, args...) -> | |
Fn.curry$ (n - args.length), (Fn.partial$ f, args) | |
curryFlip: (n, f, args...) -> | |
Fn.curry$ (n - args.length), (Fn.flip$ f, args) | |
curry$: (n, f, args...) -> | |
if n > args.length | |
Fn.partial Fn.curry$, (n - args.length), (Fn.partial$ f, args) | |
else f.apply @, args | |
Function::curry = (args...) -> | |
Fn.curry.apply @, [@length, @].concat args | |
Function::curryFlip = (args...) -> | |
Fn.curryFlip.apply @, [@length, @].concat args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment