Reputation: 41601
Recently I started learning Julia and have studied a lot of examples. I noticed the @
sign/syntax a couple of times. Here is an example:
using DataFrames
using Statistics
df = DataFrame(x = rand(10), y = rand(10))
@df df scatter(:x, :y)
This will simply create a scatterplot. You could also use scatter(df[!, :x], df[!, :y])
without the @
and get the same result. I can't find any documentation about this syntax. So I was wondering what this syntax is and when you should use this in Julia
?
Upvotes: 4
Views: 396
Reputation: 42264
When you do not know how something works try typing ?
followed by what you want to know in Julia REPL.
For an example typing ?@
and pressing ENTER yields:
The at sign followed by a macro name marks a macro call. Macros provide the ability to include generated code in the final body of a program. A macro maps a tuple of arguments, expressed as space-separated expressions or a function-call-like argument list, to a returned expression. The resulting expression is compiled directly into the surrounding code. See Metaprogramming for more details and examples.
Macros are a very advanced language concept. They generally take code as an argument and generate new code that gets compiled. Consider this macro:
macro myshow(expr)
es = string(expr)
quote
println($es," = ",$expr)
end
end
Which can be used as:
julia> @myshow 2+2
2 + 2 = 4
To understand what is really going try @macroexpand:
julia> @macroexpand @myshow 2+2
quote
Main.println("2 + 2", " = ", 2 + 2)
end
You can see that one Julia command (2+2) has been packed around with additional julia code. You can try @macroexpand
with other macros that you are using.
For more information see the Metaprogramming section of Julia manual.
Upvotes: 5
Reputation: 6395
What is @ in Julia?
Macros have a dedicated character in Julia's syntax: the @ (at-sign), followed by the unique name declared in a macro NAME ... end block.
So in the example you noted, the @df
is a macro, and the df
is its name.
Read here about macros. This concept belongs to the meta-programming feature of Julia. I guess you used the StatsPlots.jl
package since @df
is one of its prominent tools; using the @macroexpand
, you can investigate the functionality of the given macro:
julia> using StatsPlots
julia> @macroexpand @df df scatter(:x, :y)
:(((var"##312"->begin
((var"##x#313", var"##y#314"), var"##315") = (StatsPlots).extract_columns_and_names(var"##312", :x, :y)
(StatsPlots).add_label(["x", "y"], scatter, var"##x#313", var"##y#314")
end))(df))
Upvotes: 5