Interpolating an expression into an expression

I want to build a constructor with keyword arguments inside a macro, and the first keyword argument should be for the expression. I find it difficult to put this expression in the expression. Here is what I mean. Say I have a type

type Test ex end 

which contains the expression. I want to create a constructor where origex = :(a * b) is the default value from the keyword argument. I tried

 @eval :(Test(ex=$origex) = Test(origex)) 

But if you look at an expression that does:

 Test(ex=a * b) = begin # console, line 1: Test(origex) end 

you will see that this will not work, because a*b should still be an expression. So I tried

 @eval :(Test(ex=:($origex)) = Test(origex)) 

but it has an odd expression

 Test(ex=$(Expr(:quote, :($(Expr(:$, :origex)))))) = begin # console, line 1: Test(origex) end 

which will also not be eval . Instead, I need to get

 Test(ex=:(a * b)) = begin # console, line 1: Test(origex) end 

as an expression for eval, but I don't know how to get this expression in an expression.

+5
source share
1 answer

I think you need what you need. It seems you had a few errors:

 julia> type Test ex::Expr end julia> orig_ex = :(a + b) :(a + b) julia> new_ex = Meta.quot(orig_ex) :($(Expr(:quote, :(a + b)))) julia> code = :( Test(; ex=$new_ex) = Test(ex) ) :(Test(; ex=$(Expr(:quote, :(a + b)))) = begin # REPL[4], line 1: Test(ex) end) julia> eval(code) Test julia> Test() Test(:(a + b)) 
+6
source

Source: https://habr.com/ru/post/1257365/


All Articles