top | item 42403370

(no title)

mden | 1 year ago

Anyone have examples where fold leads to easier to read code than a for loop in Rust?

discuss

order

kccqzy|1 year ago

Readability is subjective. I personally find fold almost always more readable than a for loop when the accumulator variable has a simple type. This is because merely seeing fold can already telling me several things: it will iterate over the entire collection without early exits like "break" in a loop; the data dependency between each iteration is made clear into a single variable.

I find it slightly difficult to read when the accumulator variable actually has multiple parts, like a complicated tuple. It's worse when part of the accumulator is a bool indicating whether it's finished; that's just a poor emulation of "break" in a for loop.

ironhaven|1 year ago

I have used fold for converting strings to a bitset in advent of code

    let string = "ewfsan";
    let bitset = string.bytes().fold(0u32 |acc, ch| acc | 1 << (ch - b'a'));
This is a idiom that I have used many times so this being more consice than a for loop is a plus

Of course if you have never seen a syntax before it will make less sense that anything you have seen before

bippihippi1|1 year ago

afair I've mostly only used fold when doing maths not covered by the standard sum or product. Fold is similar to map reduce but it's just one expression.

Mond_|1 year ago

I find `foo.iter().map(|x| x.bar()).collect()` almost always easier to read and better at expressing intent than a for loop.

The other direction is more interesting to me: Those are the awkward cases where people sometimes overdo it with the functional iterator heavy style.