Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active March 30, 2017 23:49
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 asaaki/9991018 to your computer and use it in GitHub Desktop.
Save asaaki/9991018 to your computer and use it in GitHub Desktop.
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