微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取树节点的子计数

如何解决获取树节点的子计数

docs for Node仅提及以下方法

EqualGreaterThanGreaterThanorEqualLessthanLessthanorEqualNotEqualSliceSubscription

它确实提到了如何使用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规则声明的上下文无关的非终结符。词汇子代将lexlayoutslit匹配布局和文字。

没有所有的模式匹配:

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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?