What are macros?

Macros are functions that accept expressions, manipulate them, and return a new expression. This is best understood with a diagram:

As we know, expressions are just abstract syntax tree representations of source code. So the macro facility in Julia allows you to take any source code and generate new source code. The resulting expression is then executed as if the source code was written directly in place.

At this point, you may wonder why we cannot use regular functions to achieve the same thing. Why could we not write a function that takes expressions, generates a new expression, and then executes the resulting expression?

There are two main reasons:

  • Macro expansion happens during compilation. This means that the macro is only executed once from where it is used—for example, when a macro is called from a function, the macro is executed at the time that the function is defined so that the function can be compiled.
  • The resulting expression from a macro can be executed within the current scope. At runtime, there is no other way to execute any dynamic code within the function itself because the function, by definition, is already compiled. So, the only way to evaluate any expression is to do so in the global scope.

By the end of this chapter, you should have a better understanding of how macros work and how they differ from functions.

As we now understand what macros are, we will now continue our journey by writing our first macro.

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

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