Training Modules 2021
Basics of the Julia language

Macros

Metaprogramming

Julia code is itself data and can be manipulated by the language while it is running

Metaprogramming

  • Large influence from Lisp
  • Since Julia is entirely written in Julia, it is particularly well suited for metaprogramming

Parsing and evaluating

Let’s start with something simple:

2 + 3

How is this run internally?

Parsing and evaluating

The string "2 + 3" gets parsed into an expression:

Meta.parse("2 + 3")

Then that expression gets evaluated:

eval(Meta.parse("2 + 3"))

Macros

They resemble functions and just like functions, they accept as input a tuple of arguments

BUT macros return an expression which is compiled directly rather than requiring a runtime eval call

So they execute before the rest of the code is run

Macro’s names are preceded by @ (e.g. @time)

Macros

Julia comes with many macros and you can create your own with:

macro <name>()
    <body>
end
Questions?