[英]How do i implement this python tree linked list code in dart?
这是 python 代码
def tree(root_label, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [root_label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
return not branches(tree)
t = tree(3, [tree(1), tree(2, [tree(1), tree(1)])])
这是我在dart中对上述代码的实现。
isTree(tree) {
if ((tree is! List) | (tree.length < 1)) {
return false;
}
for (final branch in branches(tree)) {
if (!isTree(branch)) {
return false;
}
return true;
}
}
branches(tree) {
return tree.sublist(1);
}
label(tree) {
return tree[0];
}
tree(rootLabel, [branches = List.empty]) {
for (final branch in branches) {
assert(isTree(branch));
}
return ([rootLabel] + [branches]);
}
var t = tree(3, [
tree(1),
tree(2, [tree(1), tree(1)])
]);
当我尝试声明“t”时,它给出的错误太多位置 arguments。 这是 t 的预期 output。
[3, [1], [2, [1], [1]]]
python 代码的原始来源可以在这里找到https://composingprograms.com/pages/23-sequences.html#trees
我之前在 python 中尝试过这段代码,它运行良好。 在 dart 中,我遇到了上面提到的错误。
我收到此错误
<Y0>({bool growable}) => List<Y0>' is not a subtype of type 'Iterable<dynamic>
我不知道是什么导致了这个错误。 :/
isTree(tree) {
if ((tree is! List) | (tree.length < 1)) {
return false;
}
for (final branch in branches(tree)) {
if (!isTree(branch)) {
return false;
}
return true;
}
}
branches(tree) {
return tree.sublist(1);
}
label(tree) {
return tree[0];
}
tree(rootLabel, [branches = const []]) {
for (final branch in branches) {
assert(isTree(branch));
}
return ([rootLabel] + branches);
}
var t = tree(3, [
tree(1),
tree(2, [tree(1), tree(1)])
]);
LTJ 也很有帮助,但我从 redditor 那里得到了这个解决方案,显然错误是由 [branches = List.empty] 引起的 - List.empty 一直是问题! 用 const 替换它并在代码中进行一些其他小的更改有帮助!
谢谢!
命名关键字 arguments(使用{}
声明)需要在调用 function 时使用关键字。 您可能想使用命名的位置参数(用[]
声明)。 修改你的tree
function 看起来像这样:
tree(rootLabel, [branches = List.empty])
或者,如果您想保留关键字参数,请在调用 function 时使用关键字:
var t = tree(3, branches: [
tree(1),
tree(2, branches: [tree(1), tree(1)])
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.