在上面几期讨论中我们连续介绍了Free Monad。因为FP是纯函数编程,也既是纯函数的组合集成,要求把纯代码和副作用代码可以分离开来。Free Monad的程序描述(AST)和程序实现(Interpretation)关注分离(separation of concern)模式恰恰能满足FP要求。我们可以用一些代数数据类型(ADT Algebraic Data Type)来模拟功能,再把这些ADT组合起来形成AST(Abstract Syntax Tree)。AST既是对程序功能的描述,它的组成过程也就是Monadic Programming了。在另外一个过程中,我们可以按需要去实现各种Interpreter,从而达到实际运算的目的。我认为既然FP也被称为Monadic Programming,那么Free Monad应该是FP里最重要的数据结构,它的应用模式代表了主流FP,应该有个规范的具体使用方式。在本次讨论中我们将会集中对Free Monad的应用模式进行示范体验。
我们在这次示范中模拟一个针对键值存储(Key Value Store)的操作例子:
1、ADT设计
sealed trait KVS[+Next] object KVS { case class Get[Next](key: String, onValue: String => Next) extends KVS[Next] case class Put[Next](key: String, value: String, n: Next) extends KVS[Next] case class Del[Next](key: String, n: Next) extends KVS[Next]
KVS[+Next]就是一种F[A]类型。从Suspend[F[Free[F,A]]可以得出A类型即Free类型,那么Next就是一个Free类,代表Free的下一个状态。如果需要使用Next,F[_]必须是个Functor, 这样才能通过F.map(A=>B)来获取F[B],B==另一个Free。 Put,Del模拟了无返回结果指令,那么如果需要链接到下一个Free状态的话就直接把一个Free放人Next位置。Get返回一个String,onValue函数接过这个返回值再连接到下一个Free状态。
2、获取Functor实例
implicit val kvsFunctor = new Functor[KVS] { def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] = kvs match { case Get(key, onResult) => Get(key, onResult andThen f) case Put(key, value, next) => Put(key,value,f(next)) case Del(key,next) => Del(key,f(next)) } }
3、类型升格,lift to Free
implicit def kvsToFree[A](ka: KVS[A]): Free[KVS,A] = Free.liftF(ka) def put(key: String , value: String): Free[KVS,Unit] = Free.liftF(Put(key,value,())) def get(key: String): Free[KVS,String] = Free.liftF(Get(key,identity)) def del(key: String): Free[KVS,Unit] = Free.liftF(Del(key,()))
4、Composition,Free Monad组合
import KVS._ def modify(key: String, f: String => String): Free[KVS,Unit] = for { v <- Get(key,identity) _ <- Put(key,f(v), ()) } yield() //> modify: (key: String, f: String => String)scalaz.Free[Exercises.freeExamples.KVS,Unit]
5、功能描述,AST设计
val script = for { _ <- put("USA","United States Of America") _ <- put("CHN","China") _ <- put("PIL","Pilipines") _ <- put("JPN","Japan") _ <- modify("CHN",_ =>"People's Republic Of China") _ <- del("PIL") chn <- get("CHN") } yield chn //> script : scalaz.Free[Exercises.freeExamples.KVS,String] = Gosub()
使用的是独立直接升格指令函数。函数直接返回了Free类型。就像是在for-loop里进行我们熟悉的行令编程:逐条指令编写。
6、功能实现,Interpretation
a、尾递归编译,tail-recursive interpretation
def foldScript(kvs: Free[KVS,String],table: Map[String,String] = Map.empty): Map[String,String] = kvs.resume.fold ( { case Get(key,onResult) => foldScript(onResult(table(key)), table) case Put(key,value, next) => foldScript(next, table + (key -> value)) case Del(key,next) => foldScript(next, table - key) }, _ => table ) //> foldScript: (kvs: scalaz.Free[Exercises.freeExamples.KVS,String], table: Map[String,String])Map[String,String] foldScript(script,Map.empty) //> res0: Map[String,String] = Map(USA -> United States Of America, CHN -> People's Republic Of China, JPN -> Japan)
b、foldMap,高阶类型转换,Natural Transformation,F[A]~>G[A]
type KVState[A] = State[Map[String,String],A] object KvsToMap extends (KVS ~> KVState) { def apply[A](kvs: KVS[A]): KVState[A] = kvs match { case Get(key,onResult) => State { m => (m, onResult(m(key))) } case Put(key,value,next) => State { m => (m + (key -> value), next) } case Del(key,next) => State { m => (m - key, next) } } } script.foldMap(KvsToMap).run(Map.empty) //> res1: scalaz.Id.Id[(Map[String,String], String)] = (Map(USA -> United States Of America, CHN -> People's Republic Of China, JPN -> Japan),People's Republic Of China)
def goScript(kvs: Free[KVS,String],table: scala.collection.mutable.Map[String,String]):Unit = kvs.go { case Get(key,onResult) => onResult(table(key)) case Put(key,value,next) => table += (key -> value); next case Del(key,next) => table -= key; next } //> goScript: (kvs: scalaz.Free[Exercises.freeExamples.KVS,String], table: scala.collection.mutable.Map[String,String])Unit val mutableMap = scala.collection.mutable.Map[String,String]() //> mutableMap : scala.collection.mutable.Map[String,String] = Map() goScript(script,mutableMap) println(mutableMap) //> Map(JPN -> Japan, CHN -> People's Republic Of China, USA -> United States Of America)
package Exercises import scalaz._ import Scalaz._ import scala.language.higherKinds import scala.language.implicitConversions object freeExamples { sealed trait KVS[+Next] object KVS { case class Get[Next](key: String, onValue: String => Next) extends KVS[Next] case class Put[Next](key: String, value: String, n: Next) extends KVS[Next] case class Del[Next](key: String, n: Next) extends KVS[Next] implicit val kvsFunctor = new Functor[KVS] { def map[A,B](kvs: KVS[A])(f: A => B): KVS[B] = kvs match { case Get(key, onResult) => Get(key, onResult andThen f) case Put(key, value, next) => Put(key,value,f(next)) case Del(key,next) => Del(key,f(next)) } } implicit def kvsToFree[A](ka: KVS[A]): Free[KVS,A] = Free.liftF(ka) def put(key: String , value: String): Free[KVS,Unit] = Free.liftF(Put(key,value,())) def get(key: String): Free[KVS,String] = Free.liftF(Get(key,identity)) def del(key: String): Free[KVS,Unit] = Free.liftF(Del(key,())) } import KVS._ def modify(key: String, f: String => String): Free[KVS,Unit] = for { v <- Get(key,identity) _ <- Put(key,f(v), ()) } yield() val script = for { _ <- put("USA","United States Of America") _ <- put("CHN","China") _ <- put("PIL","Pilipines") _ <- put("JPN","Japan") _ <- modify("CHN",_ =>"People's Republic Of China") _ <- del("PIL") chn <- get("CHN") } yield chn def foldScript(kvs: Free[KVS,String],table: Map[String,String] = Map.empty): Map[String,String] = kvs.resume.fold ( { case Get(key,onResult) => foldScript(onResult(table(key)), table) case Put(key,value, next) => foldScript(next, table + (key -> value)) case Del(key,next) => foldScript(next, table - key) }, _ => table ) foldScript(script,Map.empty) type KVState[A] = State[Map[String,String],A] object KvsToMap extends (KVS ~> KVState) { def apply[A](kvs: KVS[A]): KVState[A] = kvs match { case Get(key,onResult) => State { m => (m, onResult(m(key))) } case Put(key,value,next) => State { m => (m + (key -> value), next) } case Del(key,next) => State { m => (m - key, next) } } } script.foldMap(KvsToMap).run(Map.empty) def goScript(kvs: Free[KVS,String],table: scala.collection.mutable.Map[String,String]):Unit = kvs.go { case Get(key,onResult) => onResult(table(key)) case Put(key,value,next) => table += (key -> value); next case Del(key,next) => table -= key; next } val mutableMap = scala.collection.mutable.Map[String,String]() goScript(script,mutableMap) println(mutableMap) }