4 ms·
Admittedly it's a worst case scenario, but the broader point still holds even with a foreach. You are still picking out each item individually instead of operat
by mekkkkkk 5y ago
Admittedly it's a worst case scenario, but the broader point still holds even with a foreach. You are still picking out each item individually instead of operating on the collection which is what you intend to do. You write "do this for every apple: peel it", instead of "peel the apples".
- tshaddox 5y agoapples.forEach(peel) is pretty clear, and the distinction is actually important for some operations which could conceivably be applied either to the whole collection or to each item in the collection and thus could be ambiguous in plain English, like “gift wrap the apples.” That could mean giftWrap(apples) or apples.forEach(giftWrap).
- Kinrany 5y agoHere's another comparison: peel and add to mixer fresh apples only. let mut mixer = Mixer::empty(); apples.for_each(|apple| { if apple.is_fresh() { mixer.add(apple.peel()); } }); let mixer = apples .filter(Apple::is_fresh) .map(Apple::peel) .fold(Mixer::empty(), Mixer::add);
- conradludgate 5y agoThey're both pretty clear but I'd prefer the second one (if you used collect instead of fold)
- Kinrany 5y agoI chose Rust syntax because it allows both chaining and using methods as functions, but avoided Rust-specific features. In addition to `collect` this example is missing `.into_iter()` that both examples would need: I interpreted `apples` as an iterator instead. Otherwise the first example would be clearer with a for loop.
- IggleSniggle 5y agoWell said! And when this clarity is lacking in a codebase, damn do I find it incredibly frustrating! Like, can’t you just tell me whether you are trying to operate on the items of the collection or the collection as a whole??? Why did you need to adopt this ambiguous formation??
- mekkkkkk 5y agoI love me some forEach methods! It's still one off from completely avoiding the loop-think though. A syntax like "apples.'peel()" (where peel is a method on the individual apples) is what I imagine. As a PS, I think the parent comment was referring to a (corresponding) "for apple in apples: peel(apple)" syntax though. The main point was that you don't have to bother with the manual index iteration as in my worst case example.