Skip to content

Instantly share code, notes, and snippets.

@ream88
Created August 17, 2019 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ream88/460c97d07166d1f4b5cedf9033681439 to your computer and use it in GitHub Desktop.
Save ream88/460c97d07166d1f4b5cedf9033681439 to your computer and use it in GitHub Desktop.
Curried functions in Elixir
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