[erlang-questions] Storing funs in term files

Steve Davis <>
Sun Apr 5 13:07:16 CEST 2009


Hi Ulf,

Matthew's answer (file:script) did actually cope with the current 
situation.

I would definitely be interested in seeing the code you wrote as it may 
inspire other approaches to the problem, which is, specifically, a 
protocol converter that uses declarative forms/formats. I needed to read 
in simple funs that apply simple transformations on particular elements 
to "tuple-ize" the input

e.g. fun([X, Y]) -> { list_to_atom(X), Y } end.

Of course, there is a strong argument to be made that I should be using 
leex/yecc for this, but... well, maybe when I put the converter up onto 
github it will be clear why I haven't!

At the very least your module sounds very interesting from a 
learning/inspiration perspective!

Best regards,
Steve


Ulf Wiger wrote:
> 
> I once wrote a small module that would find a given
> fun and fetch its abstract representation (provided
> the module was compiled with debug info).
> 
> Given the following brilliant program:
> 
> -module(m).
> 
> -export([f/2]).
> 
> 
> f(N, X) ->
>     if
>     N==1; N==2 ->
>         element(N,
>             {fun() ->
>                  X + 1
>              end,
>              fun() ->
>                  X - 1
>              end});
>     N == 3 ->
>         fun(Y) ->
>             X + Y
>         end
>     end.
> 
> Eshell V5.6.5  (abort with ^G)
> 1> m:f(1,17).
> #Fun<m.0.54764714>
> 2> extract:f(v(2)).
> {'fun',10,
>        {clauses,[{clause,10,[],[],
>                          [{op,11,'+',{var,11,'X'},{integer,11,1}}]}]}}
> 
> 
> If this approach suits you, I can send you the code.
> 
> BR,
> Ulf W
> 
> Steve Davis wrote:
>> Given that:
>> 1> A = {echo, fun(X) -> X end}.
>> {echo,#Fun<erl_eval.6.13229925>}
>>
>> I have a scenario where it would be useful to store funs in term
>> files, for example:
>>
>> % contents of the term file
>> {echo, fun(X) -> X end}.
>>
>> 2>{ok, B} = file:consult("fun.term").
>> ** exception error: no match of right hand side value
>>                     {error,{2,erl_parse,"bad term"}}
>>
>> Note that although the term file contents *passes the syntax checker*,
>> the parser declares this to be a bad term.
>>
>> Is there a way to achieve this? If not, it seems odd to me that funs
>> should be "second class citizens" in term files.
>>
>> Thanks!
>> _______________________________________________
>> erlang-questions mailing list
>> 
>> http://www.erlang.org/mailman/listinfo/erlang-questions
> 
> 




More information about the erlang-questions mailing list