Skip to content

Instantly share code, notes, and snippets.

@asaaki

asaaki/currying.ex

Last active Mar 30, 2017
Embed
What would you like to do?
Partial Functions / Currying
# 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
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