String Eval
From Erlang Community
(Difference between revisions)
| Revision as of 21:49, 18 August 2006 (edit) Cyberlync (Talk | contribs) ← Previous diff |
Revision as of 21:55, 3 September 2006 (edit) (undo) Bfulgham (Talk | contribs) Next diff → |
||
| Line 21: | Line 21: | ||
| Now, this is an admittedly baroque way to determine the value of 1 + 2, but it does give you interesting access to the inner workings of the Erlang interpreter. | Now, this is an admittedly baroque way to determine the value of 1 + 2, but it does give you interesting access to the inner workings of the Erlang interpreter. | ||
| - | [[Category:CookBook]] | + | [[Category:CookBook]][[Category:StringRecipes]] |
Revision as of 21:55, 3 September 2006
Problem
You want to evaluate Erlang code stored in a string.
Solution
Use erl_scan:string to convert the string into a list of tokens, then use erl_parse:parse_exprs to generate the Erlang intermediate representation, then finally use erl_eval:exprs to generate the final output:
1> {ok,A,B} = erl_scan:string("A = 1 + 2.").
{ok,[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}],1}
2> A.
[{var,1,'A'},{'=',1},{integer,1,1},{'+',1},{integer,1,2},{dot,1}]
3> {C,D} = erl_parse:parse_exprs(A).
{ok,[{match,1,{var,1,'A'},{op,1,'+',{integer,1,1},{integer,1,2}}}]}
4> D.
[{match,1,{var,1,'A'},{op,1,'+',{integer,1,1},{integer,1,2}}}]
5> erl_eval:exprs(D,[]).
{value,3,[{'A',3}]}
|
Now, this is an admittedly baroque way to determine the value of 1 + 2, but it does give you interesting access to the inner workings of the Erlang interpreter.

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

