假设有一个名为m的函数,调用如下所示
//foo.js
m("foo")我有一个sweet.js宏,它定义了一个名为m的宏,用于接受foo.js并展开m (基本上是在编译时运行该函数)。
在某些情况下,我不想扩展m,因为与宏不同,函数可以作为头等公民传递。
doSomething(m) //don't want to expand this as a macro如果在宏中没有覆盖此场景的情况,sweet.js会抱怨说,所以我需要一个可以扩展到相同符号的所有捕获规则。
macro m {
//simplification to demonstrate a case that recursively expand macro
case { _ ( $foo, $bar) } => { return #{m($foo)} }
//does syntax unwrapping in real case
case { _ ( $foo ) } => { return #{$foo} }
//**this tries to recursively expand `m`, which is not what I want**
case { _ } => { return #{m} }
}如何使m宏扩展到m函数,考虑到宏的其他情况确实需要将m作为宏递归展开?
发布于 2014-11-03 22:23:13
您需要let绑定宏:
let m = macro {
case { _ ( $foo, $bar) } => { return #{$foo} }
case { _ ( $foo ) } => { return #{$foo} }
// `m` is bound to the surrounding scope, not the macro
case { _ } => { return #{m} }
}编辑:
对不起,你的问题第一次没有看完:)
这里有一个更好的解决方案,您只需要将它分成两个不同的宏,一个可以执行实际的递归工作,另一个可以处理非递归的基本情况:
function m() {}
macro m_impl {
case { _ ( $foo, $bar) } => { return #{m_impl($foo)} }
case { _ ( $foo ) } => { return #{$foo} }
}
let m = macro {
case { _ ($foo, $bar) } => { return #{m_impl($foo, $bar)} }
case { _ } => { return #{m} }
}
m (100, 200);
doSomething(m)https://stackoverflow.com/questions/26655750
复制相似问题