[erlang-questions] How to wrap a function of any arity

Richard A. O'Keefe <>
Mon Nov 20 02:28:46 CET 2006


"Ludovic Coquelle" <> wrote:
	Sorry I did not give a good explanation of what I try to do.  I
	would like to write the function "wrap_fun" so that I can call
	it with different inner functions.  Let say I have different functions:
	compute_one/1
	compute_two/2

	I would like to be able to write:
	Log_compute_one = wrap_fun(compute_one, logger),
	Log_compute_two = wrap_fun(compute_two, logger).
	
I'm sorry, but that makes me feel ill.  Just because the Erlang *compiler*
doesn't require types doesn't mean that an Erlang *designer* can ignore them.

You could quite easily write wrap_fun/2 so that it *accepts* functions of
any arity but delivers a function of one argument, a list:

    wrap_fun(Module, Name, Pid) ->
	fun (Argument_List) -> Pid ! apply(Module, Name, Argument_List) end.

But it would be better to do something like

    wrap_fun0(F, P) ->
	fun () -> F() ! P end.

    wrap_fun1(F, P) ->
	fun (X1) -> F(X1) ! P end.

    ...

    wrap_fun9(F, P) ->
	fun (X1,X2,X3,X4,X5,X6,X7,X8,X9)->F(X1,X2,X3,X4,X5,X6,X7,X8,X9)!P end.

and then write

	Log_compute_one = wrap_fun1(compute_one, logger),
	Log_compute_two = wrap_fun2(compute_two, logger).




More information about the erlang-questions mailing list