Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into a fun

Tags:

erlang

I'm trying to get around a problem with file:consult/1 not allowing tuples with fun in them like in this example:

{add_one, fun(X) -> X+1 end}.

To get around this I'm considering writing the fun inside a string and evaluating it

{add_one, "fun(X) -> X+1 end"}.

The question is. How do I convert the string into a fun?

like image 715
Jon Gretar Avatar asked Jan 05 '10 20:01

Jon Gretar


2 Answers

parse_fun_expr(S) ->
  {ok, Ts, _} = erl_scan:string(S),
  {ok, Exprs} = erl_parse:parse_exprs(Ts),
  {value, Fun, _} = erl_eval:exprs(Exprs, []),
  Fun.

Note that you need a period at the end of your fun expression, e.g. S = "fun(X) -> X + 1 end.".

like image 175
Zed Avatar answered Sep 24 '22 02:09

Zed


file:script/1 almost does what you want - it evaluates a series of erlang expressions from a file and returns the last result. You could use it in place of file:consult/1 but you'd need to change the format of the file from "term. term. term." giving [term, term ,term] to "[term, term , term]." giving [term, term, term] - place a single expression in the file instead of a sequence.

like image 43
archaelus Avatar answered Sep 23 '22 02:09

archaelus