Evaluating expressions

We have looked at creating expression objects in great detail. But how are they useful? Remember that an expression object is just an abstract syntax tree representation of a Julia program. At this point, we can ask the compiler to continue translating the expression into executable code and then run the program. 

Expression objects can be evaluated by calling the eval function. Essentially, the Julia compiler will go through the rest of the compilation process and run the program. Now, let's start a fresh, new REPL and run the following code:

Clearly, it's just a simple assignment. We can see that the x variable is now defined in the current environment:

Note that the evaluation of the expression actually happens in the global scope. We can prove this by running eval from within a function:

This is not an unimportant observation! At first glance, we may have expected the y variable to be assigned inside the foo function; however, the variable assignment happened in the global scope instead, so the variable was defined in the current environment as a side-effect.

More precisely, the expression is evaluated in the current module. Since we are testing in the REPL, the evaluation was done in the current module, called Main. The expression is designed as such because eval is commonly used for code generation, which can be useful in defining variables or functions within the module.

Next, we will learn how to create expression objects more easily.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.119.17