设为首页 加入收藏

TOP

Scalaz(43)- 总结 :FP就是实用的编程模式(二)
2017-10-10 12:12:54 】 浏览:8895
Tags:Scalaz 总结 就是 实用 编程 模式
logToFree[A](da: Dialog[A]) = Free.liftF(da)

 

3、AST:代数程序,描述程序功能

 

object FreeASTs { import FreeADTs._ val prg: Free[Dialog,Unit] = for { x <- Ask("What's your first name?") _ <- Tell(s"Hi, $x") y <- Ask("What's your last name?") _ <- Tell(s"Hello $x $y!!!") } yield() }

 

4、Interpret:把F[A]对应到G[A]上。G[A]是实现具体效果的Monad。以下提供了两种不同效果的实现方式

object FreeInterp { import FreeADTs._ object DialogConsole extends (Dialog ~> Id) { def apply[A](da: Dialog[A]): Id[A] = da match { case Ask(p) => println(p); readLine case Tell(s) => println(s) } } type WF[A] = Map[String,String] => A type Tester[A] = WriterT[WF,List[String],A] implicit val testerMonad = WriterT.writerTMonad[WF,List[String]] def testerToWriter[A](f: Map[String,String] => (List[String],A)) = WriterT[WF,List[String],A](f) object DialogTester extends (Dialog ~> Tester) { def apply[A](da: Dialog[A]): Tester[A] = da match { case Ask(p) => testerToWriter {m => (List(),m(p))} case Tell(s) => testerToWriter {m => (List(s),())} } } }

5、Run:最后,对实现方式进行运算

object SimpleFree extends App { import FreeASTs._ import FreeInterp._ //prg.foldMapRec(DialogConsole)
 prg.foldMapRec(DialogTester).run( Map("What's your first name?" -> "Johnny", "What's your last name?" -> "Foo") )._1.map(println) }

如果出现多种模拟语法的情况,我们可以用inject方式把各种语法注入Coproduct,形成一个多语法的语句集合。具体的语法集合以及多语法的效果实现对应运算可以参考前面这篇博客中的讨论

 

 

 

 

 

 

 

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇scala学习手记4 - Java基本类型对.. 下一篇Windows和Linux(Ubuntu)下安装S..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目