1. 程式人生 > >深圳scala-meetup-20180902(2)- Future vs Task and ReaderMonad依賴注入

深圳scala-meetup-20180902(2)- Future vs Task and ReaderMonad依賴注入

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