Convert a string into a fun

erlang

Solution

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."`.

Problem

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?

Original source

Related problems