BEGIN TYPING YOUR SEARCH ABOVE AND PRESS RETURN TO SEARCH. PRESS ESC TO CANCEL

Evaluate an Erlang Expression

When creating my final year project – Interactive Erlang Notebook – I had to figure out a way of evaluating Erlang expressions. This means taking a line of Erlang code (in string format) and executing it using Erlang.

You’d think it would be easy, but it took a bit longer than expected. Sifting through StackOverflow and going past the first page on a google search, things weren’t looking good.

Quick and Easy

Luckily, after reading the Erlang Docs, I figured it out. Below is an implementation of a function that evaluates Erlang code (in string format) and returns the result.

Here we have a function that tokenises the string, parses the expression and evaluates it.

Too easy, right? Kind of.

Variable Bindings

But what happens if we want to keep track of variable bindings? Think of variable bindings as a history of previously assigned variables. If you keep track of the bindings, you will be able to reference them in other Erlang expressions that you execute later on.

Another way of thinking about it is it’s like the Erlang shell. When you type A = 100. in the shell and press Enter, that assigns the integer 100 to the variable A. On the next Erlang shell prompt, you can type A. , press Enter, and the number 100 will be output.

This feature is very useful, and was a simple, but huge and important milestone in the development of IErlang

In Erlang, bindings are represented as a list of tuples. Each tuple consists of two elements:

  • The variable name
  • The variable value

Example:

Below is an example of executing Erlang expressions whilst keeping track of variable bindings:

In the code above, we return a tuple which contains the a success message, the value of code execution and the list of bindings.
When originally calling the execute function, you should pass an empty list to the function where it expects a list of bindings.

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked