Home > Blockchain >  if there is [1::] in dart?
if there is [1::] in dart?

Time:01-18

In python we can write recursive function to count an element in a list like this:

def count(list):
if list == []:
return 0

return 1   count(list[1::])

But if there is the method or something else to create this line of code return 1 count(list[1::]) in Dart?

I think, that we can do something like this using the dart collections like

var result = (1   a.sum);
return result;

Now I try to solve this task like this:

void main() {
  List<int> n = [2, 6, 7]; //the arrays of element

  int sumsReccur(List<int> n) {
    if (n.length <= 0) {
      return 0; //base case
    }
  }

  var result = 1   sumsReccur(n.length);

  return result;
}

CodePudding user response:

Dart has lazy iterables, which is more likely to be what you want. The way to do iterable[1::] is iterable.skip(1).

It's still horribly inefficient, but you can do:

  int count(Iterable values) {
    if (values.isEmpty) return 0;
    return 1   count(values.skip(1));
  }

It's still going to take O(n^2) time to count the number of elements of values, but since it's lazy, it won't copy the elements too, so it only does O(n) memory allocation.

In practice, never do this if you care about performance. It's better to iterate on the iterator:

int count(Iterable values) {
  int countIterator(Iteartor iterator) {
    if (iterator.moveNext()) return 1   count(itearator);
    return 0;
  }
  return countIterator(values.iterator);
}

Again, the recursion here is trivial, and recursing on an iterator is usually a bad idea (better to have a loop, because there are limits to the recursion stack size, and you have no control over the depth of the recursion this way.)

When dealing with lists or iterables, the preferred way to access them is by iterating in a loop (for (var v in values) ... or for (var i = 0; i < list.length; i ) ... list[i] ...), or with a helper function like values.forEach((value) { doSomething(value); });.

All you're calculating her is values.length anyway, so it's not hard to do better than recursion.

CodePudding user response:

You can use the sublist method:

int sumsReccur(List<int> n) {
  if (n.length <= 0) {
    return 0; //base case
  }
  return subReccur(n.sublist(1));
}
  •  Tags:  
  • Related