Created
August 17, 2019 11:54
-
-
Save ream88/460c97d07166d1f4b5cedf9033681439 to your computer and use it in GitHub Desktop.
Curried functions in Elixir
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 Curry do | |
defmacro curry([{name, arity}]) do | |
(arity - 1) | |
|> Range.new(0) | |
|> Enum.map(fn arity -> | |
arguments = | |
Range.new(0, arity) | |
|> Enum.filter(&(&1 > 0)) | |
|> Enum.map(&"a#{&1}") | |
|> Enum.map(&String.to_atom/1) | |
|> Enum.map(&Macro.var(&1, nil)) | |
case arguments do | |
[] -> | |
quote do | |
def unquote(name)() do | |
&unquote(name)(&1) | |
end | |
end | |
arguments -> | |
quote do | |
def unquote(name)(unquote_splicing(arguments)) do | |
&unquote(name)(unquote_splicing(arguments), &1) | |
end | |
end | |
end | |
end) | |
end | |
end | |
defmodule Math do | |
import Curry | |
def add(a, b), do: a + b | |
curry add: 2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment