As mentioned in the Intro to Expressions expressions are a specific type of object in Julia. As such, they have fields. The two most used fields of an expression are its head
and its args
. For instance, consider the expression
MyExpr3 = Expr(:(=), :x, 2)
discussed in Creating Expressions. We can see the head
and args
as follows:
julia> MyExpr3.head
:(=)
julia> MyExpr3.args
2-element Array{Any,1}:
:x
2
Expressions are based on prefix notation. As such, the head
generally specifies the operation that is to be performed on the args
. The head must be of Julia type Symbol
.
When an expression is to assign a value (when it gets evaluated), it will generally use a head of :(=)
. There are of course obvious variations to this that can be employed, e.g.:
ex1 = Expr(:(+=), :x, 2)
:call for expression heads
Another common head
for expressions is :call
. E.g.
ex2 = Expr(:call, :(*), 2, 3)
eval(ex2) ## 6
Following the conventions of prefix notation, operators are evaluated from left to right. Thus, this expression here means that we will call the function that is specified on the first element of args
on the subsequent elements. We similarly could have:
julia> ex2a = Expr(:call, :(-), 1, 2, 3)
:(1 - 2 - 3)
Or other, potentially more interesting functions, e.g.
julia> ex2b = Expr(:call, :rand, 2,2)
:(rand(2,2))
julia> eval(ex2b)
2x2 Array{Float64,2}:
0.429397 0.164478
0.104994 0.675745
Automatic determination of head
when using :()
expression creation notation
Note that :call
is implicitly used as the head in certain constructions of expressions, e.g.
julia> :(x + 2).head
:call
Thus, with the :()
syntax for creating expressions, Julia will seek to automatically determine the correct head to use. Similarly:
julia> :(x = 2).head
:(=)
In fact, if you aren't certain what the right head to use for an expression that you are forming using, for instance, Expr()
this can be a helpful tool to get tips and ideas for what to use.