4 ms·
Nah. It involves multiple passes and setting the answer to the wrong value before (hopefully) setting it to the right value. Plus it forces you out of whateve
by mrkeen 16d ago
Nah. It involves multiple passes and setting the answer to the wrong value before (hopefully) setting it to the right value.
Plus it forces you out of whatever lazy/streaming paradigm you had going on. If your foldr produces a list, downstream can start consuming it in constant memory as long as you let it do its thing.
- 8note 16d agofold kinda does too, for setting the first combined value that you are assembling, and thus on an empty list you end up with that wrong value, same as the for loop
- mrkeen 16d agoNo, the sum of the first ten natural numbers is always 55. It is not "initialised" to some other number beforehand.
- bspammer 16d agojapgolly’s signature for reduce above is slightly wrong, it should be `[A] -> ((A,A) -> A) -> Maybe A`. I.e. there is no initial value to pass in, but the result is an Optional to handle the empty iterator case. That’s how rust does it, for example: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.reduce https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
- KPGv2 16d agoIf your data should not be successfully folded if it's empty, you should've already parsed it as an Optional nonEmptyList instead of letting illegal states fly around for a while in your application.
- bspammer 16d agoYeah that's good application design, but those concerns aren't so relevant to the person writing the standard library for a language. You can certainly include a specialized version of reduce for nonEmptyLists which just returns A, but that doesn't change the fact that you have to return an Optional for a normal possibly-empty iterator if you want your reduce function to be non-partial.