How do i implement this python tree linked list code in dart?

Question:

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 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)])])

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!

Asked By: zram

||

Answers:

Named keyword arguments (declared with using {}) require keyword to be used when calling the function. You probably wanted to use named positional argument (declared with []). Modify your tree function to look like this:

tree(rootLabel, [branches = List.empty])

Or if you want to keep the keyword argument, use the keyword when calling the function:

var t = tree(3, branches: [
    tree(1),
    tree(2, branches: [tree(1), tree(1)])
]);
Answered By: LTJ
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.