Evaluating a string of code in Erlang at runtime

Did you know that Erlang has the ability to read in a string representing a line of code to execute at runtime? It can parse it out, evaluate it and return the value. Let’s see how… Evaluating Simple Expressions At its most basic, we can just read any expression passed in and execute it. -module(parser). -export([ evaluate_expression/1 ]). -spec evaluate_expression(string) -> any(). evaluate_expression(Expression) -> {ok, Tokens, _} = erl_scan:string(Expression), % scan the code into tokens {ok, Parsed} = erl_parse:parse_exprs(Tokens), % parse the tokens into an abstract form {value, Result, _} = erl_eval:exprs(Parsed, []), % evaluate the expression, return the value Result. Let’s try passing in some simple arithmetic expressions, remembering that statements end in commas and functions with a period, so our strings need to include those punctuations: ...

March 5, 2017