[erlang-questions] Auto generated functions

Attila Babo babo.online@REDACTED
Mon Feb 4 23:39:33 CET 2008


I wrote a simple Y combinator to deal with tail-recursive anonymous
functions. There are several showcase implementations for Erlang
already, but for practical purposes you need to deal with arity. Here
is my code with examples, I'm looking for a way to avoid this
boilerplate code. For practical reasons it's OK to generate it up to a
point by hand or use a single tuple as a parameter, but I'm looking
for "nicer" solution. Any suggestions?

Attila

%% Y Combinator

y(F) ->
	{arity, Arity} = erlang:fun_info(F(F), arity),
	G = case Arity of
		0 -> fun(H) -> F(fun() -> (H(H))() end) end;
		1 -> fun(H) -> F(fun(A) -> (H(H))(A) end) end;
		2 -> fun(H) -> F(fun(A, B) -> (H(H))(A, B) end) end;
		3 -> fun(H) -> F(fun(A, B, C) -> (H(H))(A, B, C) end) end;
		4 -> fun(H) -> F(fun(A, B, C, D) -> (H(H))(A, B, C, D) end) end;
		5 -> fun(H) -> F(fun(A, B, C, D, E) -> (H(H))(A, B, C, D, E) end) end
	end,
	G(G).

%% Examples

dots() ->
	(y:y(fun(F) -> fun() -> io:fwrite("."), F() end end))().

len(I) when is_list(I) ->
	(y(fun(F) -> fun(X, N) -> case X of [] -> N; [_|R] -> F(R, N+1) end
end end))(I, 0).

%% End of code

http://www.erlang.org/ml-archive/erlang-questions/200301/msg00053.html
http://bc.tech.coop/blog/070611.html



More information about the erlang-questions mailing list