Combinators: and_then

map() was described as a chainable way to simplify match statements.
However, using map() on a function that returns an Option<T> results
in the nested Option<Option<T>>. Chaining multiple calls together can
then become confusing. That’s where another combinator called and_then(),
known in some languages as flatmap, comes in.

and_then() calls its function input with the wrapped value and returns the result. If the Option is None, then it returns None instead.

In the following example, cookable_v2() results in an Option<Food>.
Using map() instead of and_then() would have given an
Option<Option<Food>>, which is an invalid type for eat().

  1. #![allow(dead_code)]
  2. #[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }
  3. #[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }
  4. // We don't have the ingredients to make Sushi.
  5. fn have_ingredients(food: Food) -> Option<Food> {
  6. match food {
  7. Food::Sushi => None,
  8. _ => Some(food),
  9. }
  10. }
  11. // We have the recipe for everything except Cordon Bleu.
  12. fn have_recipe(food: Food) -> Option<Food> {
  13. match food {
  14. Food::CordonBleu => None,
  15. _ => Some(food),
  16. }
  17. }
  18. // To make a dish, we need both the ingredients and the recipe.
  19. // We can represent the logic with a chain of `match`es:
  20. fn cookable_v1(food: Food) -> Option<Food> {
  21. match have_ingredients(food) {
  22. None => None,
  23. Some(food) => match have_recipe(food) {
  24. None => None,
  25. Some(food) => Some(food),
  26. },
  27. }
  28. }
  29. // This can conveniently be rewritten more compactly with `and_then()`:
  30. fn cookable_v2(food: Food) -> Option<Food> {
  31. have_ingredients(food).and_then(have_recipe)
  32. }
  33. fn eat(food: Food, day: Day) {
  34. match cookable_v2(food) {
  35. Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
  36. None => println!("Oh no. We don't get to eat on {:?}?", day),
  37. }
  38. }
  39. fn main() {
  40. let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi);
  41. eat(cordon_bleu, Day::Monday);
  42. eat(steak, Day::Tuesday);
  43. eat(sushi, Day::Wednesday);
  44. }

See also:

closures, Option, and Option::and_then()