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

Gaspar Chilingarov nm@REDACTED
Fri Nov 17 22:31:14 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).
>

you can test function arity and wrap it in a different ways.
2> F = fun(X) -> ok end.
#Fun<erl_eval.6.56006484>
3> is_function(F).
true
4> is_function(F, 1).
true
5> is_function(F, 2).
false


so your code should look like this:

wrap_fun(Fun, Pid) ->
   case Fun of
   Fun when is_function(Fun, 1) ->
       fun(AllArgs) ->
           Res = Fun(AllArgs),
           Pid ! Res
       end;
   Fun when is_function(Fun, 2) ->
       fun(X, X1) ->
           Res = Fun(X, X1),
           Pid ! Res
       end;
   ...
   end.

This is a little bit ugly, but should work.
In other hand, if you use functions with arity > 10 - I think it's
better to fix programming style, than write wrapper function to any
arity. Usually most of that arguments should be packet in a some State
record/tuple.


>
> On 11/18/06, t ty <tty.erlang@REDACTED> wrote:
>>
>> Unfortunately I'm not very sure what you need. You can always encode
>> all the params into a list also funs can also take multi params
>>
>> wrap_fun(Fun, Pid) ->
>>    fun(One, Two, Three) ->
>>      Res = Fun(One, Two, Three)
>>      Pid ! Res
>>    end.
>>
>> t
>>
>> On 11/17/06, Ludovic Coquelle <lcoquelle@REDACTED> wrote:
>> > I would like to wrap a function into another which send the the result
>> of
>> > the inner function to some external process.
>> > Let say I have a function called "compute" and a log process
>> "logger": I
>> > want to create a new function with something like:
>> >
>> > Log_compute = wrap_fun(compute, logger).
>> >
>> >  wrap_fun(Fun, Pid) ->
>> >     fun(AllArgs) ->
>> >          Res = Fun(AllArgs),
>> >         Pid ! Res
>> >      end.
>> >
>> > But I don't know how to do that with a function of any arity (the code
>> above
>> > work only for function of arity 1).
>> > Is this do-able? if not, how should I do?
>> >
>> >
>> > _______________________________________________
>> > erlang-questions mailing list
>> > erlang-questions@REDACTED
>> > http://www.erlang.org/mailman/listinfo/erlang-questions
>> >
>> >
>> >
>>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions


-- 
Gaspar Chilingarov

System Administrator,
Network security consulting

t +37493 419763 (mob)
i 63174784
e nm@REDACTED



More information about the erlang-questions mailing list