3 ms·
Oh, duh. Thanks. Thats https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or https://doc.rust-lang.org/stable/std/option/enum.Option.html.
by steveklabnik 7y ago
Oh, duh. Thanks.
Thats https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or https://doc.rust-lang.org/stable/std/option/enum.Option.html..., I think?
- saagarjha 7y agoIf 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")
- remcob 7y agoTo 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.)
- tomcatfish 7y agoThat function is exactly what is posted above you, it just has a different name than it does in Haskell.
- remcob 7y agoThe 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-Maybe.html#v: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.)