1. 程式人生 > >深圳scala-meetup-20180902(1)- Monadic 程式設計風格

深圳scala-meetup-20180902(1)- Monadic 程式設計風格

type FoodName = String type Quantity = Int type FoodStore = KVStore[String,Int] def addFood(food: FoodName, qty: Quantity )(implicit fs: FoodStore): Future[Unit] = for { current <- fs.read(food) newQty = current.map(cq => cq + qty ).getOrElse(qty) _ <- fs.update(food, newQty) }
yield () def takeFood(food: FoodName, qty: Quantity)(implicit fs: FoodStore): Future[Quantity] = for { current <- fs.read(food) instock = current.getOrElse(0) taken = Math.min(instock,qty) left = instock - taken _ <- if (left > 0) fs.update(food,left) else fs.delete(food) }
yield taken def cookSauce(qty: Quantity)(get: (FoodName,Quantity) => Future[Quantity], put:(FoodName,Quantity) => Future[Unit]): Future[Quantity] = for { tomato <- get("Tomato",qty) veggie <- get("Veggie",qty) garlic <- get("Garlic", qty * 3
) sauceQ = tomato / 2 + veggie * 3 / 2 _ <- put("Sauce",sauceQ) } yield sauceQ def cookMeals(qty: Quantity)(get: (FoodName,Quantity) => Future[Quantity], put: (FoodName,Quantity) => Future[Unit]): Future[Quantity] = for { pasta <- get("Pasta", qty) sauce <- get("Sauce", qty) _ <- get("Spice",10) meals = Math.min(pasta,sauce) _ <- put("Meal", meals) } yield meals