Last active
November 14, 2023 15:06
-
-
Save satom99/ae4567b0894d381a3867dfacbfd4c4c0 to your computer and use it in GitHub Desktop.
Elixir 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
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