Remix.run Logo
Hackbraten 5 hours ago

I think that in every imperative language that offers `map`, `filter`, `reduce`, or similar, the written contract of this API should state that any higher-order function handed to it as an argument must be free from side effects.

I think I’ve seen several language core APIs have this in their contract, e.g. `Stream#reduce` in Java [0] (emphasis mine):

> accumulator - an *associative, non-interfering, stateless* function for combining two values

[0]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/S...

speedstyle an hour ago | parent [-]

In Rust these specifically take `FnMut`, a function which can update internal/borrowed state, rather than `Fn` which can't easily. In `map` or `filter` you shouldn't rely on the iteration order so that's not often useful – maybe something 'logically' stateless but which needs a mutable connection/threadpool/cache, or eg a counter which is really an ancillary reduction. There's even `inspect` which is explicitly for such side effects. In `fold`, the order is guaranteed and you could use it for a state machine, a fiddly `zip` with other mutable iterators, etc – something you need to perform the reduction, but which isn't really an output, I think you could reasonably write either

    .fold(init, move |acc, x| {…})  // or
    .fold((state, init), |(state, acc), x| {…}).1