[erlang-questions] Storing funs in term files

Ulf Wiger <>
Sun Apr 5 08:54:50 CEST 2009


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


-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com



More information about the erlang-questions mailing list