让树数据结构定义如下:
一棵树有一个节点作为它的根。节点要么是叶子,要么是具有一个或多个节点作为其子节点的内部节点。
在某种伪 OO 编程语言中,我们可以定义这样的树:
Node := InnerNode | Leaf
Leaf {
isLeaf() : TRUE
}
InnerNode {
isLeaf() : FALSE
children() : List<Node>
}
Tree {
root() : Node
}
现在我们可以定义两个函数,“bad_code”和“good_code”。函数 'bad_code' 不编译,其他函数编译:
function bad_code(Node anyNode) : void {
// this will give a compile time error "type Node does not define method children()"
anyNode.children();
}
function good_code(Node anyNode) : void {
// the compiler understands that all Nodes must have a method called isLeaf() which
// returns a boolean
let b : boolean <- anyNode.isLeaf();
if (b == FALSE) {
// this will not give a compile time error because the compiler can deduce that
// anyNode must be of type InnerNode which has the method children()
anyNode.children();
}
}
问题:
- 以上是否是以某种官方方式定义/描述的语言功能的示例?
- 如果是这样:这种语言功能的正式名称是什么?
- 是否有任何实现此语言功能的现实世界编程语言?
- 这种语言功能可以实现为运行时零成本的编译时检查吗?