Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterable lazy functions getting too lazy

Tags:

dart

This code trips me up. In this code the takeWhile makes sense - take up debits, reducing the balance while the balance is positive. The problem is with this code nothing happens. No calls to balance.debit() are made and I guess the reason is takeWhile filtering happens lazily.

I can ensure that it gets called by tacking on a toList() call, but that seems wasteful as a list is not really needed.

  • What is a better way to do this?
  • Is takeWhile not the right tool for this job?

Code follows:

class Balance {
  Balance(this._balance);
  double _balance;
  debit(double amount) {
    print('Debiting $amount');
    return (_balance -= amount);
  }
}

main() {
  final balance = new Balance(3.0);
  final debits = [ 1.0, 2.0, 3.0 ];
  debits.takeWhile((debit) => balance.debit(debit) > 0);

  //////////////////////
  //debits
  //  .takeWhile((debit) => balance.debit(debit) > 0)
  //  .toList();
}
like image 332
user1338952 Avatar asked Sep 18 '25 00:09

user1338952


1 Answers

No, takeWhile is not the right tool for this job.

As you noticed, it is lazy. It is intended to create a new iterable, and it only does something if you actually use that iterable. Here, you are not interested in the result at all, so you just want the "while" part, and don't care about the "take". Alternative:

for (debit in debits) {
  if (balance.debit(debit) < 0) break;
}

I even find it easier to read.

like image 158
lrn Avatar answered Sep 20 '25 13:09

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!