julia

What is the difference between `:` and `quote` expressions in Julialang?


I don't fully understand what the difference between quote ... end and :( ... ) expressions are in Julia.

It looks as if the only difference is that the former (quote) introduces additional comment lines.

Here's some examples

julia> :(2+2)
:(2 + 2)

julia> e1=:(2+2)
:(2 + 2)

julia> e1
:(2 + 2)

julia> eval(e1)
4
julia> quote
           2+2
       end
quote
    #= REPL[2]:2 =#
    2 + 2
end

julia> e2=quote
           2+2
       end
quote
    #= REPL[5]:2 =#
    2 + 2
end

julia> e2
quote
    #= REPL[5]:2 =#
    2 + 2
end

julia> eval(e2)
4

I found this wikibook, but it only says that

the helpful line numbers that have been added to each line of the quoted expression

(referring to quote compared to :).

The documentation pages for keyword expressions also didn't say too much.

Unlike the other means of quoting, :( ... ), this form introduces QuoteNode elements to the expression tree, which must be considered when directly manipulating the tree.

What does this mean?


Solution

  • They are very similar. :(...) is designed for single line quotes, while quote adds linenumber nodes which mean that if the code has errors, the line of the error will be reported better if the code spans several lines.