Skip to content

Instantly share code, notes, and snippets.

@HernanRivasAcosta
Last active August 29, 2015 14:07
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 HernanRivasAcosta/93d6384b69c208b73ecf to your computer and use it in GitHub Desktop.
Save HernanRivasAcosta/93d6384b69c208b73ecf to your computer and use it in GitHub Desktop.
Partial application in erlang!
partial_application(F, Args) ->
{arity, InitialArity} = erlang:fun_info(F, arity),
case length(Args) of
L when L < InitialArity ->
MissingArgs = [{var, 1, N} || N <- lists:seq(1, InitialArity - L)],
ArgList = [case is_function(A) of
false -> erl_parse:abstract(A);
true -> {var, 1, erlang:fun_to_list(A)}
end || A <- Args] ++ MissingArgs,
Parsed = [{'fun', 1,
{clauses, [{clause, 1, MissingArgs, [],
[{call, 1, {var, 1, 'F'}, ArgList}]}]}}],
{value, R, _} = erl_eval:exprs(Parsed, [{'F', F}] ++
[{erlang:fun_to_list(A), A} ||
A <- Args, is_function(A)]),
R
end.
@HernanRivasAcosta
Copy link
Author

Usage:

F = partial_application(fun(X, Y) -> X + Y end, [1]).
F(2). % 3

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