Skip to content

Instantly share code, notes, and snippets.

@satom99
Last active November 14, 2023 15:06
Show Gist options
  • Save satom99/ae4567b0894d381a3867dfacbfd4c4c0 to your computer and use it in GitHub Desktop.
Save satom99/ae4567b0894d381a3867dfacbfd4c4c0 to your computer and use it in GitHub Desktop.
Elixir currying
defmodule Currying do
def function ~> argument when is_function(function) do
curry(function, argument)
end
def curry(function, arguments) when is_function(function) and is_list(arguments) do
{:arity, arity} = Function.info(function, :arity)
arguments = Enum.reverse(arguments)
do_curry(function, arity, arguments)
end
def curry(function, argument) when is_function(function) do
curry(function, [argument])
end
def curry(function) when is_function(function) do
curry(function, [])
end
defp do_curry(function, arity, arguments) when length(arguments) > arity do
raise BadArityError, function: function, args: arguments
end
defp do_curry(function, arity, arguments) when length(arguments) < arity do
fn argument ->
do_curry(function, arity, [argument | arguments])
end
end
defp do_curry(function, arity, arguments) when length(arguments) == arity do
arguments = Enum.reverse(arguments)
apply(function, arguments)
end
end
import Currying
test = fn a, b, c -> {a, b, c} end
curry(test).(1).(2).(3)
curry(test, [1]).(2).(3)
curry(test, [1, 2]).(3)
curry(test, [1, 2, 3])
curry(test, [1, 2, 3, 4])
(test ~> 1).(2).(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment