>
> is it good idea to use eval within a macro?
No, using `eval` inside of a macro is strongly discouraged (search the
mailing list for previous discussions as to why). Using `parse` this way is
similarly discouraged -- and also unnecessary.
One way to think of macros is as a game. You start with some piece of
*quoted* code:
mycode = quote
type MyType1
a
end
end
You win the game by making a macro that produces the same thing as the
"quoted expression" above. How you know if you win? By using `macroexpand`.
This is why you need to read the manual -- to know the rules and to learn
how to use the tools. Here's a simplified example to get you going:
julia> macro makemytype(name)
typename = esc(name) # <- name here is a "symbol"
code = quote
type $typename # <- $typename is "interpolation"
a
end
end
return code
end
julia> macroexpand( :(@makemytype MyType1) )
quote # In[1], line 4:
type MyType1 # In[1], line 5:
a
end
end
On Tue, Oct 20, 2015 at 4:06 PM, <[email protected]> wrote:
> macro mymac(args...)
> typname = args[1]
> priv_typname= esc(string("priv_",trait.name))
> #code
> code = quote
> #create a type
> eval(parse(string("type ", $(priv_typname), " end")))
> end
> return code
> end
>
> Still couldn't get it to work, and i don't see what I am missing?
> One more question, is it good idea to use eval within a macro?
> thanks
>
> On Tuesday, October 20, 2015 at 12:14:37 PM UTC-7, Isaiah wrote:
>>
>> Please do work through the examples in the Metaprogramming section of the
>> manual to learn how to take apart and reassemble expressions to do what you
>> need:
>>
>> http://docs.julialang.org/en/release-0.4/manual/metaprogramming/
>>
>> There are tools (such as `macroexpand`) introduced in the manual that
>> will help you debug this kind of issue.
>>
>> In general, when asking questions on the list, please:
>> - search for previous discussions (such as this one:
>> https://groups.google.com/forum/#!searchin/julia-users/type$20macro/julia-users/r9sGn-k7SDw/Xm0nKsKBBJYJ
>> )
>> - provide a complete example. "this is what i am doing in the macro"
>> does not provide enough context.
>>
>> Thanks!
>>
>> On Tue, Oct 20, 2015 at 3:02 PM, <[email protected]> wrote:
>>
>>> Hi fellows,
>>>
>>> Question 1:
>>>
>>> I am trying to generate a type in a macro and expect to see it in the
>>> calling context.
>>> this is what i am doing in the macro:
>>> code = quote eval(parse(string("type ", $(priv_typname), " end"))) end
>>>
>>> here is what is returned from the macro
>>> eval(parse(string("type ",$(Expr(:escape, "priv_Eq"))," end")))
>>>
>>> but in the julia shell, when i try to do this :
>>>
>>> julia> a = priv_Eq()
>>> ERROR: UndefVarError: priv_Eq not defined
>>>
>>> can somebody tell me why and what I am doing wrong?
>>>
>>>
>>> Question 2:
>>>
>>> I am also trying to generate a parametrized type like:
>>>
>>> type Eq{T,S}
>>> end
>>>
>>> any suggestions to append the type_params to the type programmatically?
>>>
>>> Thanks
>>>
>>>
>>>
>>>
>>>
>>>
>>