Here is the python code
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 Falsefor branch in branches(tree):if not is_tree(branch):return Falsereturn Truedef is_leaf(tree):return not branches(tree)t = tree(3, [tree(1), tree(2, [tree(1), tree(1)])])
Here is my implementation of the above code in 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 = const []]) {for (final branch in branches) {assert(isTree(branch));}return ([rootLabel] + branches);
}var t = tree(3, [tree(1),tree(2, [tree(1), tree(1)])
]);
When i try to declare "t" it is giving the error too many positional arguments. This is the expected output of t.
[3, [1], [2, [1], [1]]]
Original source of python code can be found here https://composingprograms.com/pages/23-sequences.html#trees
I have tried this code in python before and it works perfectly. In dart I am running into errors i have mentioned above.
I am getting this error
<Y0>({bool growable}) => List<Y0>' is not a subtype of type 'Iterable<dynamic>
I can't figure out whats causing this error. :/
LTJ was also helpful, but i got this solution from a redditor, apparently the error was being caused by
[branches = List.empty] - List.empty
was the problem all along!
Replacing it with const []
and making some other small changes in the
code helped!!
tHANKS!