Constructing expression objects manually

As an expression is just a data structure, we can easily construct them programmatically. Understanding how to do this is essential for metaprogramming, which involves creating new code structures on the fly.

The Expr constructor has the following signature:

Expr(head::Symbol, args...)

The head node always carries a symbol. The arguments just contain whatever the head node expects—for example, the simple expression x + y can be created as follows:

Of course, we can always create a nested expression if we want to:

At this point, you may wonder whether there is an easier way to create expressions without having to construct Expr objects manually.  For sure, it can be done as shown below:

Basically, we can wrap any expression with :( on the left and ) on the right. The code that sits inside will not be evaluated, but will instead be parsed into an expression object; however, this way of quoting only works with a single expression—if you try to do this with multiple expressions, an error will be displayed, as shown in the following code:

It does not work because multiple expressions should be wrapped with begin and end keywords. So it would be fine if we entered the following code block:

The result is a little interesting. As you can see, the code is now wrapped within a quote/end block rather than a begin/end block. It actually makes sense because a quoted expression is being displayed rather than the original source code. Remember, this is the abstract syntax tree rather than the original code.

It also turns out that quote/end can be used directly to create expressions:

We have now learned how to parse source code into an expression object. Next, we will look into more complex expressions so that we are more familiar with the basic code structure of Julia programs.

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

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