在以下创建链表的程序中,assert 有什么用?不是没用吗?


bool isTree(List<Object> tree) {
if ((tree is! List) | (tree.length < 1)) {
return false;
}
for (final branch in branches(tree)) {
if (!isTree(branch)) {
return false;
}
}
return true;
}
List branches(List tree) {
return tree.sublist(1);
}
Object label(List tree) {
return tree[0];
}
List tree(rootLabel, [List branches = const []]) {
for (final branch in branches) {
assert(isTree(branch));
}
return ([rootLabel] + branches);
}
bool isLeaf(List tree) {
return branches(tree).isEmpty;
}
var t = tree('hey', [
tree('hello'),
tree('hum', [tree('there'), tree('hey')])
]);

如果我移除带有assert函数的for循环,以及is_tree函数,程序仍然会返回与它们相同的结果,那么它们不是没用吗?


List branches(List tree) {
return tree.sublist(1);
}
Object label(List tree) {
return tree[0];
}
List tree(rootLabel, [List branches = const []]) {

return ([rootLabel] + branches);
}
bool isLeaf(List tree) {
return branches(tree).isEmpty;
}
var t = tree('hey', [
tree('hello'),
tree('hum', [tree('there'), tree('hey')])
]);

这是我学习的完整教程https://composingprograms.com/pages/23-sequences.html#trees

它可以确保所有分支都是树。如果没有断言,您就可以在没有任何错误的情况下编写此语句。

var t = tree('hey', ['notATree']);

使用断言,它将抛出一个错误。

最新更新