设为首页 加入收藏

TOP

深圳scala-meetup-20180902(1)- Monadic 编程风格(二)
2019-08-15 00:11:32 】 浏览:165
Tags:深圳 scala-meetup-20180902 Monadic 编程 风格
ath.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

上面几个操作函数都是Future类型的,具体的操作都包含在for{...}里。我们看到:在for{...}里可以产生中间结果、也可以直接写运算表达式、也可以使用这些中间运算结果。for{...}里的情景就像正常的行令式编程。然后我们又对这些操作函数进行组合:

   implicit val refrigerator = new FoodStore val shopping: Future[Unit] = for { _ <- addFood("Tomato", 10) _ <- addFood("Veggie", 15) _ <- addFood("Garlic", 42) _ <- addFood("Spice", 100) _ <- addFood("Pasta", 6) } yield () val cooking: Future[Quantity] = for { _ <- shopping sauce <- cookSauce(10)(takeFood(_,_),addFood(_,_)) meals <- cookMeals(10)(takeFood(_,_),addFood(_,_)) } yield (meals) val todaysMeals = Await.result(cooking,3 seconds) println(s"we have $todaysMeals pasta meals for the day.")

最后组合成这个cooking monad, 然后一次性Await.result(cooking...)获取最终结果。通过上面这个例子我们可以得到这么一种对Monadic编程风格的感觉,就是:用for-comprehension来组合,组合、再组合,然后run(Await.result)获取结果。

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇PICE(6):集群环境里多异类端点.. 下一篇深圳scala-meetup-20180902(2)-..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目