macros - 将宏变量传递给函数进行插值
问题描述
我正在尝试编写一个评估表达式然后将其与一些值进行比较的宏。对于这篇文章,我已将问题简化为一个较小的示例。
macro small_bad(item)
quote
$(use_val(esc(item)))
end
end
function use_val(val)
quote
if $val == 1
1
elseif $val == 2
2
else
-1
end
end
end
因为我不想多次评估 expr,所以我想将它保存在一个变量中。所以我尝试了这个:
macro small_good(item)
quote
begin
val = $(esc(item))
$(begin
use_val(val)
end)
end
end
end
但是后来我val
在@small_good
.
我也尝试过传递use_val(:val)
,但这也失败了,因为宏系统将重命名
val
为其他名称。
我怎样才能做到这一点?
编辑: 给定第一个答案,我在实际代码中尝试了这个
macro match(item, arms)
var = gensym(:var)
quote
let $var = $(esc(item))
$(begin
code = :nothing
for e in reverse(filter((e) -> e isa Expr, arms.args))
code = make_match(var, e, code)
end
code
end)
end
end
end
并得到UndefVarError: ##var#253 not defined
免责声明:我知道@match
宏已经在 Match.jl 包中实现,我正在重新实现它的一个子集作为学习练习
编辑2:
我想到了。在使用了 François Févotte 的建议后,我现在不得不更改我的真实版本,use_val
而$(esc(val))
不是$val
.
我的错误是没有包括那个细节。将更新要点以反映这一点
解决方案
如果我明白你想要什么,这应该有效:
macro small(item)
var = gensym(:var)
quote
let $var = $(esc(item))
$(use_val(var))
end
end
end
function use_val(val)
quote
if $val == 1
1
elseif $val == 2
2
else
-1
end
end
end
它扩展为:
julia> using MacroTools
julia> MacroTools.@expand @small myexpr
quote
let octopus = myexpr
begin
if octopus == 1
1
elseif octopus == 2
2
else
-1
end
end
end
end
并且既没有卫生问题,也没有多重评估问题:
# Testing in a local scope introduced by `let`
# is a good way to check for hygiene issues
julia> let arg = [1]
@small pop!(arg)
end
1
现在我猜你原来的问题的很多实质已经在 MWE 创建过程中丢失了,因为这一切本质上等同于:
julia> function small(val)
if val == 1
1
elseif val == 2
2
else
-1
end
end
small (generic function with 1 method)
julia> let args = [1]
small(pop!(args))
end
1
推荐阅读
- vue.js - 如何减小v-switch的宽度
- python - python pandas excel
- android - 如何在android的mp图表中每小时添加条并对齐每个顶部标签
- python - 如何将火炬张量转换为浮点数?
- sql - Oracle Apex - 用线条或颜色分隔卡片文本行
- angular - 保存 mat-stepper 状态并在页面刷新时将其传递给相同的 mat-stepper
- mysql - MySQL SELECT 在 SELECT 子句或 WHERE 子句中,以便进一步过滤
- node.js - UnhandledPromiseRejectionWarning: TypeError: questionList is not iterable
- r - trycatch 在 R 中只返回警告而不是错误
- sql - 只取行集中的第一行