Using the postwalk function

In order to traverse the whole abstract syntax tree, we can use the MacroTool's postwalk function. To understand how it works, we can play with a simple example, as outlined in the following steps:

  1. Let's create an expression object as follows:

Here, we have used the rmlines function to remove the line number nodes since we do not need them in this exercise.

  1. Then, we can use the postwalk function to traverse the tree and display everything that it has ever encountered:

The postwalk function accepts a function as its first argument and an expression as the second argument. As it traverses the tree, it calls the function with the sub-expression being visited. We can see that it considered every single leaf node (for example, :x) as well as every sub-tree from the expression such as :(x = 1). It also includes the top-level expression as we can see at the bottom of the output. 

If we pay a little more attention to the order of the traversal, we realize that the postwalk function works from the bottom up, starting from the leaf nodes.

MacroTools also provides a prewalk function that also traverses the tree. The difference between prewalk and postwalk is that prewalk would work from the top down rather than bottom up. You are encouraged to try that out and learn how they differ. 

For our use case, we can use either one.

Now that we know how to match expressions and traverse the tree, we have everything in our toolbox to develop our DSL. That's the fun part. Let's go!

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

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