4 ms·
The problem with .map().collect()? is that it does not short-circuit. Consider: for item in iterable.iter() { item.foo()?; } You will exit the loop a
by linkdd 4y ago
The problem with .map().collect()? is that it does not short-circuit.
Consider:
for item in iterable.iter() {
item.foo()?;
}
You will exit the loop as soon as there is an error. But with .map().collect(), you iterate over the whole list, and then exit if one of the items yield an error.
EDIT: Thank you for your answers, it seems I was wrong and it does short-cricuit!
- nynx 4y agoCollecting into a result will short circuit.
- anon291 4y agoRealistically, the 'problem' is that many programmers today get scared away when you start mentioning monads or effect systems. Realistically though, the solution is to have first class monads or effect systems in rust and other languages. A lot of language design today is 'wasted' in the sense that we spend time implementing special cases (Promises in javascript, ? syntax in rust, async syntax in rust) without any thought given to the meta problem. In my opinion, the lack of attention to the meta problem is due to programmers being scared of such topics.
- chrismorgan 4y agoIncorrect: collecting to a Result stops on the first error, as documented explicitly in https://doc.rust-lang.org/std/result/enum.Result.html#method.from_iter https://doc.rust-lang.org/std/result/enum.Result.html#method....
- NobodyNada 4y agoThat's not true: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=226af340b7c47f3ccf25024049f595f6 https://play.rust-lang.org/?version=stable&mode=debug&editio... let v: Option<Vec<i32>> = (0..5).map(|i| { print!("{i} "); if i == 3 { None } else { Some(i) } }).collect(); // prints 0 1 2 3
- remram 4y agoShort-circuit refers to stopping not skipping.
- fnordpiglet 4y agoI don’t understand. The example you replied to stopped, not skipped.
- aPoCoMiLogin 4y agothat should print 4 and 5 if that was skipping ?
- remram 4y agoYeah I read too fast. One of the issues with type inference, this exact same code does different things depending on whether the result is assigned to `Option<Vec<i32>>` or `Vec<Option<i32>>`
- tuetuopay 4y agoMap and friends are lazy, so the whole chain is run once and in full for each item. Collect will short circuit at the first Err encountered. You can even try it out by using `.inspect()` in the chain to see that the iterations don't go past the first error.
- SuperCuber 4y agoExcept it does! https://doc.rust-lang.org/src/core/result.rs.html#2029 https://doc.rust-lang.org/src/core/result.rs.html#2029