将表达式内插到表达式中 [英] Interpolating an Expression into an Expression

查看:95
本文介绍了将表达式内插到表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用宏内部的关键字参数构建一个构造函数,并且第一个关键字参数需要用于表达式.我在将该表达式放入表达式时遇到麻烦.这就是我的意思.说我有类型

I want to build a constructor with keyword arguments inside of a macro, and the first keyword argument needs to be for an expression. I am having trouble putting that expression into the expression. Here's what I mean. Say I have a type

type Test
  ex
end

其中包含一个表达式.我想创建一个构造函数,其中origex = :(a * b)是关键字参数的默认构造函数.我尝试过

which holds an expression. I want to make a constructor where origex = :(a * b) is the default from a keyword argument. I tried

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

但是,如果您看一下这样的表达式:

But if you look at the expression that makes:

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

您会看到它不起作用,因为a*b仍需要是一个表达式.所以我尝试了

you see that it won't work because the a*b needs to still be an expression. So I tried

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

但是这个表达式很奇怪

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

,也不会eval.相反,我需要获取

which also won't eval. Instead I need to get

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

作为eval的表达式,但我不知道如何将该表达式转换为表达式.

as the expression to eval, but I don't know how to get that expression into an expression.

推荐答案

我认为以下是您想要的.您似乎犯了一些错误:

I think the following is what you want. You seem to have had a few mistakes:

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))

这篇关于将表达式内插到表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆