From: Siraaj Khandkar Date: Wed, 29 Apr 2015 00:00:55 +0000 (-0400) Subject: Implement automatic currying. X-Git-Tag: 3.1.0^0 X-Git-Url: https://git.xandkar.net/?a=commitdiff_plain;h=e033aadea66cc7f68e3a66cde23a2edfe4c4e9e6;p=hope.git Implement automatic currying. --- diff --git a/src/hope.app.src b/src/hope.app.src index 9d0ece1..f04e3ae 100644 --- a/src/hope.app.src +++ b/src/hope.app.src @@ -1,7 +1,7 @@ {application, hope, [ {description, "Higher Order Programming in Erlang"}, - {vsn, "3.0.0"}, + {vsn, "3.1.0"}, {registered, []}, {applications, [ kernel, diff --git a/src/hope_fun.erl b/src/hope_fun.erl index 61babe9..5ee6730 100644 --- a/src/hope_fun.erl +++ b/src/hope_fun.erl @@ -2,9 +2,23 @@ -export( [ id/1 + , curry/1 ]). -spec id(A) -> A. id(X) -> X. + +-spec curry(fun()) -> + fun(). +curry(F) -> + {value, {arity, Arity}} = lists:keysearch(arity, 1, erlang:fun_info(F)), + curry(F, [], Arity). + +-spec curry(fun(), list(), integer()) -> + fun(). +curry(F, Args, 0) -> + apply(F, lists:reverse(Args)); +curry(F, Args, Arity) -> + fun (X) -> curry(F, [X | Args], Arity - 1) end. diff --git a/test/hope_fun_SUITE.erl b/test/hope_fun_SUITE.erl index d4e2281..910cc49 100644 --- a/test/hope_fun_SUITE.erl +++ b/test/hope_fun_SUITE.erl @@ -9,6 +9,7 @@ %% Test cases -export( [ t_id/1 + , t_curry/1 ]). @@ -26,6 +27,7 @@ all() -> groups() -> Tests = [ t_id + , t_curry ], Properties = [parallel], [ {?GROUP, Properties, Tests} @@ -39,3 +41,20 @@ groups() -> t_id(_Cfg) -> X = foo, X = hope_fun:id(X). + +t_curry(_Cfg) -> + Single = fun (X) -> X end, + Double = fun (X, Y) -> {X, Y} end, + Triple = fun (X, Y, Z) -> {X, Y, Z} end, + + F = hope_fun:curry(Single), + a = F(a), + + G1 = hope_fun:curry(Double), + G = G1(a), + {a, b} = G(b), + + H1 = hope_fun:curry(Triple), + H2 = H1(a), + H = H2(b), + {a, b, c} = H(c).