Re:Rust's Poor Composability
by chrismorgan on Thursday April 06, 2023 @11:10AM
(#35469381)
Incorrect: collecting to a Result stops on the first error, as documented explicitly in https://doc.rust-lang.org/std/result/enum.Result.html#method....
Map 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.
Collecting into a result will short circuit.
Re:Rust's Poor Composability
by NobodyNada on Thursday April 06, 2023 @11:10AM
(#35469386)
That's not true: 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 3Short-circuit refers to stopping not skipping.
Re:Rust's Poor Composability
by fnordpiglet on Thursday April 06, 2023 @12:01PM
(#35470312)
I don’t understand. The example you replied to stopped, not skipped.
Re:Rust's Poor Composability
by aPoCoMiLogin on Friday April 07, 2023 @09:38AM
(#35481437)
that should print 4 and 5 if that was skipping ?
Yeah 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>>`
Re:Rust's Poor Composability
by SuperCuber on Thursday April 06, 2023 @11:12AM
(#35469412)
Except it does! https://doc.rust-lang.org/src/core/result.rs.html#2029
Realistically, 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.
Consider:
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!