I am trying to create a string literal macro in Julia to create a symbol
, so that s"x"
is the same as :x
. It does not work:
julia> macro s_str(p)
symbol(p)
end
julia> s'x'
ERROR: s not defined
julia> s"x"
ERROR: x not defined
Macros also don’t require commas or parenthesis. Consider this example, where the @time macro takes a Julia expression type and times its evaluation. In order to create a macro in Julia, we can just use “ macro”. This can be applied to both functions, as well as an expression to perform normal logic as we would in a function.
A quote with source code inside returns an expression object that describes this code. The expression we return from a macro is spliced into the place where the macro call happens, as if you really had written the macro result there. That’s the reason why a macro can’t technically do more than any old Julia code.
The : character has two syntactic purposes in Julia. The first form creates a Symbol, an interned string used as one building-block of expressions: julia> s = :foo :foo julia> typeof (s) Symbol The Symbol constructor takes any number of arguments and creates a new symbol by concatenating their string representations together:
There are various ways to create expressions in Julia, some of them are listed below: Julia provides a pre-defined function Expr () that can be used to create expressions of user’s choice. Here, my_exp = Expr (: (=), :x, 10) is the prefix notation of the syntax, the first argument is head and the remaining are arguments of the expression.
The reason is macro hygiene. You can do either
macro s_str(p)
quote
symbol($p)
end
end
which is easy to read, or do the more complicated but equivalent.
macro s_str(p)
esc(:(symbol($p)))
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With