Expressions are a specific type of object in Julia. You can think of an expression as representing a piece of Julia code that has not yet been evaluated (i.e. executed). There are then specific functions and operations, like eval()
which will evaluate the expression.
For instance, we could write a script or enter into the interpreter the following: julia> 1+1 2
One way to create an expression is using the :()
syntax. For example:
julia> MyExpression = :(1+1)
:(1 + 1)
julia> typeof(MyExpression)
Expr
We now have an Expr
type object. Having just been formed, it doesn't do anything - it just sits around like any other object until it is acted upon. In this case, we can evaluate that expression using the eval()
function:
julia> eval(MyExpression)
2
Thus, we see that the following two are equivalent:
1+1
eval(:(1+1))
Why would we want to go through the much more complicated syntax in eval(:(1+1))
if we just want to find what 1+1 equals? The basic reason is that we can define an expression at one point in our code, potentially modify it later on, and then evaluate it at a later point still. This can potentially open up powerful new capabilities to the Julia programmer. Expressions are a key component of metaprogramming in Julia.