Hacker News new | ask | show | jobs
by remcob 2258 days ago
To match the semantics of a 'fold' the closure would have to receive two arguments: the default value and the Some value.

(I don't think Option has such a function, and I don't see why it should.)

1 comments

That function is exactly what is posted above you, it just has a different name than it does in Haskell.
The function in Option linked above by steveklabnik has signature

    fn map_or(self, default: U, f: FnOnce(T) -> U) -> U
a fold has the signature

    fn fold(self, init: U, f: FnMut(U, T) -> U) -> U
The difference is in the closure. in map_or the closure gets called at most once with one argument, in fold it can get called many times with two arguments. This makes `map_or` and `fold` distinct functions. While you could argue that the distinction between FnOnce and FnMut is Rust specific, the difference in number of arguments should also exist in Haskell. And in fact in Haskell the `map_or` function is called `maybe`:

https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-...

(I'd argue the name `map_or` is more descriptive than `maybe`, although it does lift the result out of the Option monad which is unconventional for a map.)