Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a macro for creating a symbol in Julia

Tags:

macros

julia

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
like image 290
asmeurer Avatar asked Oct 28 '14 02:10

asmeurer


People also ask

How do I create a macro in Julia?

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.

Why can’t a macro do more than any old Julia code?

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.

What is the use of symbol in Julia?

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:

How to create expressions in Julia?

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.


Video Answer


1 Answers

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
like image 87
IainDunning Avatar answered Sep 19 '22 00:09

IainDunning