rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.73k stars 12.5k forks source link

Option and_then documentation clarity #114493

Closed Dev380 closed 1 month ago

Dev380 commented 1 year ago

https://github.com/rust-lang/rust/blob/e173a8e6634d787a1529ff6ec5dc63273425ca34/library/core/src/option.rs#L1381C8-L1381C8

Hi, I have a concern about the documentation here. It says that other languages call and_then a flat map operation. However, some searching has led me to this SO answer which leads me to believe that this could be more accurately be called "functor map", which is what haskell's fmap means, according to the answer. This also has the benefit of improved clarity and reducing confusion with the iterator flat map operation.

the8472 commented 1 year ago

Well, haskell isn't the only other language in existence. Java calls it flatMap for example.

jdahlstrom commented 1 year ago

Option::and_then is not the functorial map. That's Option::map. and_then is the monadic "bind" operation and in Haskell it's spelled >>=. The reason it's often called flat_map (including by Rust's iterators) is that it's semantically a composition of map and flatten.

For example,

Some(42).map(|x| if x == 42 { Some("The answer") } else { None })

returns a nested Option<Option<&str>>, which is often not what you want, but

Some(42).and_then(|x| if x == 42 { Some("The answer") } else { None })

returns a "flattened" Option<&str>. This allows you to chain an arbitrary number of Option-returning operations without ending up with an Option<Option<…Option<T>…>>.

Dylan-DPC commented 1 month ago

Closing this as it's not a issue and the documentation is as intended.