Macros and Metaprogramming Techniques

This chapter will discuss two of the most powerful facilities in the Julia programming language: macros and metaprogramming.

In a nutshell, metaprogramming is a technique for writing code that generates code—that's why it has the prefix meta. It may sound esoteric, but it is a fairly common practice in many programming languages today. For example, C compiler uses a preprocessor to read source code and produce new source code, and then the new source code is compiled into a binary executable. For example, you can define a MAX macro, as in #define MAX(a,b) ((a) > (b) ? (a) : (b)), and this means that every time we use MAX(a,b), it is replaced with ((a) > (b) ? (a) : (b)). Note that MAX(a,b) is much easier to read than the longer form.

The history of metaprogramming is quite long. As far back as the 1970s, it was already popular among the LISP programming language community. Interestingly, the LISP language is designed in such a way that the source code is structured like data—for example, a function call in LISP looks like (sumprod x y z), where the first element is the name of the function and the rest are arguments. Since it is really just a list of four symbols—sumprod, x, y, and zwe can take this code and manipulate it in any way—for example, we can expand it so it calculates both the sum and product of the numbers, so the generated code becomes (list (+ x y z) (* x y z))

You may wonder whether we can just write a function for that. The answer is, yes: in both of the examples that we just looked at, there is no need to use a metaprogramming technique. The examples were there only to illustrate how metaprogramming works. In general, we can say that metaprogramming is not needed 99% of the time; however, there is still that remaining 1% of cases where metaprogramming would be very useful. The first section will explore use cases where we would want to use metaprogramming.

In this chapter, we will learn several metaprogramming facilities in Julia. The following topics will be covered in particular:

  • Understanding the need for metaprogramming
  • Working with expressions
  • Developing macros
  • Using generated functions
..................Content has been hidden....................

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