Today I realized that it would be possible to implement currying-capability in Elixir, using some clever anonymous function creation. (‘continuation-style currying’).
There was already a library called curry, which required you to define your to-be-curried functions using a special macro. And it would then define 255(the max. arity in Elixir) different function heads for it.
Currying does not do that. Instead, when yo u call
curry, the passed function is wrapped in an anonymous function accepting a single parameter. This anonymous function is constructed in a clever way that will re-construct a new anonymous function each time an argument is passed, until the original function’s arity is reached, in which case the original function is called and the result returned.
There’s also some niceties like
curry_many which allows you to pass in a list of arguments to apply to a curried function at the same time, and an optional implementation of
~> as infix-variant of
iex> use Currying iex> enum_map = curry(&Enum.map/2) iex> partially_applied_enum_map = enum_map.([1,2,3]) iex> results = partially_applied_enum_map.(fn x -> x*x end) [1,4,9]
See the Currying library/hex package here!
I’d be very grateful for any feedback ;-).