secret
Last active

Tools to partially apply functions with their arguments.

  • Download Gist
curry.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.