如何解决获取树节点的子计数
docs for Node仅提及以下方法:
Equal
,GreaterThan
,GreaterThanorEqual
,Lessthan
,LessthanorEqual
,NotEqual
,Slice
,Subscription
它确实提到了如何使用Subscription
来按索引访问子节点,但是我如何找出要遍历子节点的子节点数呢?
这是我的用例:
Exp parsed = parse(#Exp,"2+(4+3)*48");
println("the number of root children is: " + size(parsed));
但是它会产生错误,因为size()
似乎只适用于List
。
解决方法
不同的答案,不同的方面是好是坏。这里有一些:
import ParseTree;
int getChildrenCount1(Tree parsed) {
return (0 | it + 1 | _ <- parsed.args);
}
getChildrenCount1
遍历解析树节点的原始子级。这包括空格和注释节点(layout
)和关键字(literals
)。您可能需要过滤这些内容,或按除法进行补偿。
另一方面,这似乎有点间接。我们也可以直接要求子列表的长度:
import List;
import ParseTree;
int getChildrenCount2(Tree parsed) {
return size(parsed.args) / 2 + 1; // here we divide by two assuming every other node is a layout node
}
还有元数据的方式。每个解析树节点都直接在其中有生产的声明性描述,可以查询和探索:
import ParseTree;
import List;
// immediately match on the meta-structure of a parse node:
int getChildrenCount3(appl(Production prod,list[Tree] args)) {
return size(prod.symbols);
}
此符号的长度应与args的长度相同。
// To filter for "meaningful" children in a declarative way:
int getChildrenCount4(appl(prod(_,list[Symbol] symbols,_),list[Tree] args)) {
return (0 | it + 1 | sort(_) <- symbols);
}
sort
过滤器用于使用syntax
规则声明的上下文无关的非终结符。词汇子代将lex
和layouts
和lit
匹配布局和文字。
没有所有的模式匹配:
int getChildrenCount4(Tree tree) {
return (0 | it + 1 | s <- tree.prod.symbols,isInteresting(s));
}
bool isInteresting(Symbol s) = s is sort || s is lex;
,
到目前为止,这似乎可行,但这很糟糕:
int getChildrenCount(Tree parsed) {
int infinity = 1000;
for (int i <- [0..infinity]) {
try parsed[i];
catch: return i;
}
return infinity;
}
void main() {
Exp parsed = parse(#Exp,"132+(4+3)*48");
println("the number of root children is: ");
println(getChildrenCount(parsed));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。