Last active
March 30, 2017 23:49
-
-
Save asaaki/9991018 to your computer and use it in GitHub Desktop.
Partial Functions / Currying
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
# Another example for: http://onor.io/2014/03/31/partial-function-application-in-elixir/ | |
defmodule PartFuncs do | |
defp addfun(x, y), do: x + y | |
# return a partially applied function | |
def add(a), do: &addfun(a, &1) | |
# could also easily be written as: addfun(a, b) | |
def add(a, b), do: (&addfun/2).(a, b) | |
end | |
# USAGE | |
partfun = PartFuncs.add(22) | |
#=> #Function<0.115088320/1 in PartFuncs.add/1> | |
partfun.(20) | |
#=> 42 | |
PartFuncs.add(22).(20) | |
#=> 42 |
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
PartFuncs = { | |
add: function (a, b) { | |
// implementation of the logic | |
var addfun = function (x, y) { return (x + y) } | |
if (typeof b === "undefined") { | |
// a function which holds the partially applied value | |
return (function (value) { | |
return addfun(this, value) | |
}).bind(a) | |
} else { | |
return addfun(a, b) | |
} | |
} | |
} | |
// USAGE | |
var partfun = PartFuncs.add(22) | |
//=> function () { [native code] } | |
partfun(20) | |
//=> 42 | |
PartFuncs.add(22)(20) | |
//=> 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment