Forked from patrickgombert/gist:4737bb75d3983d2c6512
Last active
August 29, 2015 14:12
-
-
Save styx/ea8760a47c8f13cac6fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Curried do | |
defmacro defc({name, _, args}, [do: body]) do | |
curried_args = Enum.map(Enum.with_index(args), fn({_, index}) -> | |
Enum.take(args, index + 1) | |
end) | |
for a <- curried_args do | |
if a == Enum.at(curried_args, Enum.count(curried_args) - 1) do | |
quote do | |
def unquote(name)(unquote_splicing(a)) do | |
unquote(body) | |
end | |
end | |
else | |
quote do | |
def unquote(name)(unquote_splicing(a)) do | |
fn(next) -> unquote(name)(unquote_splicing(a), next) end | |
end | |
end | |
end | |
end | |
end | |
end | |
defmodule CurriedTest do | |
use ExUnit.Case, async: true | |
defmodule CurriedExample do | |
import Curried | |
defc foobar(one, two, three) do | |
one + two + three | |
end | |
end | |
test "curries" do | |
assert CurriedExample.foobar(1).(2).(3) == 6 | |
assert CurriedExample.foobar(1, 2).(3) == 6 | |
assert CurriedExample.foobar(1, 2, 3) == 6 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment