Skip to content

Instantly share code, notes, and snippets.

@xandkar
Last active November 22, 2017 02:55
Show Gist options
  • Save xandkar/3deed1716ff35848bd1c to your computer and use it in GitHub Desktop.
Save xandkar/3deed1716ff35848bd1c to your computer and use it in GitHub Desktop.
Automatic currying in Erlang
-module(curry).
-export([curry/1]).
curry(F) ->
{arity, Arity} = erlang:fun_info(F, arity),
curry(F, [], Arity).
curry(F, Args, 0) ->
apply(F, lists:reverse(Args));
curry(F, Args, Arity) ->
fun (X) -> curry(F, [X | Args], Arity - 1) end.
@xandkar
Copy link
Author

xandkar commented Apr 28, 2015

$ erl
Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V5.10.4  (abort with ^G)
1>
1> F = fun (A, B) -> {A, B} end.
#Fun<erl_eval.12.80484245>
2>
2> G = curry:curry(F).
#Fun<curry.0.129706704>
3>
3> F(a, b).
{a,b}
4>
4> (G(a))(b).
{a,b}
5>
5> G2 = G(a).
#Fun<curry.0.129706704>
6>
6> G2(b).
{a,b}
7>
7> Plus = curry:curry(fun (X, Y) -> X + Y end).
#Fun<curry.0.129706704>
8>
8> Plus3 = Plus(3).
#Fun<curry.0.129706704>
9>
9> Plus3(7).
10
10>
10> Plus3(2).
5
11>
11> Plus3(8).
11
12>
12> Plus5 = Plus(5).
#Fun<curry.0.129706704>
13>
13> Plus3(5).
8
14> Plus5(5).
10
15>

@xandkar
Copy link
Author

xandkar commented Apr 29, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment