【发布时间】:2011-04-01 17:35:06
【问题描述】:
我有一个抽象类和案例类的树状结构,代表一种小语言的抽象语法树。
对于顶级抽象类,我实现了一个方法map:
abstract class AST {
...
def map(f: (AST => AST)): AST = {
val b1 = this match {
case s: STRUCTURAL => s.smap(f) // structural node for example IF(expr,truebranch,falsebranch)
case _ => this // leaf, // leaf, like ASSIGN(x,2)
}
f(b1)
}
...
smap 的定义如下:
override def smap(f: AST => AST) = {
this.copy(trueb = trueb.map(f), falseb = falseb.map(f))
}
现在我正在编写不同的“转换”来插入、删除和更改 AST 中的节点。
例如,从块中删除相邻的 NOP 节点:
def handle_list(l:List[AST]) = l match {
case (NOP::NOP::tl) => handle_list(tl)
case h::tl => h::handle_list(tl)
case Nil => Nil
}
ast.map {
case BLOCK(listofstatements) => handle_list(listofstatements)
}
如果我这样写,我最终会得到MatchError,我可以通过将上面的映射更改为:
ast.map {
case BLOCK(listofstatements) => handle_list(listofstatements)
case a => a
}
我应该只接受所有这些case a => a,还是可以以某种方式改进我的map 方法(或其他部分)?
【问题讨论】:
标签: scala functional-programming map