# Combinators: `and_then`

`and_then()`は引数として与えられた関数にラップされた値を渡しますが、その値が`None`だった場合は`None`を返します。

``````#![allow(dead_code)]

#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }
#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }

// We don't have the ingredients to make Sushi.
// 我々は寿司の材料を持っていない
fn have_ingredients(food: Food) -> Option<Food> {
match food {
Food::Sushi => None,
_           => Some(food),
}
}

// We have the recipe for everything except Cordon Bleu.
// コルドン・ブルー(Cordon Bleu)のレシピも持っていない。
fn have_recipe(food: Food) -> Option<Food> {
match food {
Food::CordonBleu => None,
_                => Some(food),
}
}

// To make a dish, we need both the recipe and the ingredients.
// We can represent the logic with a chain of `match`es:
// 料理を作るためには、材料とレシピの両方が必要。
// ロジックの流れを`match`のチェインで表す。
fn cookable_v1(food: Food) -> Option<Food> {
match have_recipe(food) {
None       => None,
Some(food) => have_ingredients(food),
}
}

// This can conveniently be rewritten more compactly with `and_then()`:
// `and_then()`を用いることで、同じことをよりコンパクトに表現できる。
fn cookable_v3(food: Food) -> Option<Food> {
have_recipe(food).and_then(have_ingredients)
}

// Otherwise we'd need to `flatten()` an `Option<Option<Food>>`
// to get an `Option<Food>`:
fn cookable_v2(food: Food) -> Option<Food> {
have_recipe(food).map(have_ingredients).flatten()
}

fn eat(food: Food, day: Day) {
match cookable_v3(food) {
Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
None       => println!("Oh no. We don't get to eat on {:?}?", day),
}
}

fn main() {
let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi);

eat(cordon_bleu, Day::Monday);
eat(steak, Day::Tuesday);
eat(sushi, Day::Wednesday);
}``````