Hacker News new | ask | show | jobs
by steveklabnik 2258 days ago
Oh, duh. Thanks.

Thats https://doc.rust-lang.org/stable/std/option/enum.Option.html..., I think?

2 comments

If the team had just written Haskell for a year they would have picked the obviously superior "fold" name for this operation. (I think you can actually use fold here if you really wanted it, since Option implements IntoIter?):

   Some(0).iter().fold("some", |_, _| "none")
For people coming from a functional programming background, `fold` might be the superior name. But setting aside monads, `map_or` expresses the intent much better I find.
(I was being mostly sarcastic.)
Rereading your comment I wonder how I could miss this!
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.)

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.)