Skip to content

Instantly share code, notes, and snippets.

@zfogg
Last active October 1, 2015 14:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zfogg/9d69011f501437217c6e to your computer and use it in GitHub Desktop.
Save zfogg/9d69011f501437217c6e to your computer and use it in GitHub Desktop.
Tools to partially apply functions with their arguments.
# 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