很多函数式编程爱好者都把FP称为Monadic Programming,意思是用Monad进行编程。我想FP作为一种比较成熟的编程模式,应该有一套比较规范的操作模式吧。因为Free能把任何F[A]升格成Monad,所以Free的算式(AST)、算法(Interpreter)关注分离(separation of concern)模式应该可以成为一种规范的FP编程模式。我们在前面的几篇讨论中都涉及了一些AST的设计和运算,但都是一些功能单一,离散的例子。如果希望通过Free获取一个完整可用的程序,就必须想办法把离散的Free AST组合成一体运算。我们先从单一的Free AST例子开始:
import scalaz._
import Scalaz._
import scala.language.higherKinds
import scala.language.implicitConversions
object FreeModules {
object FreeInteract {
trait Interact[+A]
type FreeInteract[A] = Free.FreeC[Interact,A]
object Interact {
case class Ask(prompt: String) extends Interact[String]
case class Tell(msg: String) extends Interact[Unit]
implicit def interactToFreeC[A](ia: Interact[A]) = Free.liftFC(ia)
object InteractConsole extends (Interact ~> Id) {
def apply[A](ia: Interact[A]): Id[A] = ia match {
case Ask(p) => println(p); readLine
case Tell(m) => println(m)
}
}
}
import Interact._
val interactScript = for {
first <- Ask("What's your first name?")
last <- Ask("What's your last name?")
_ <- Tell(s"Hello ${first} ${last}, nice to meet you!")
} yield ()
}
}
object freePrgDemo extends App {
import FreeModules._
import FreeInteract._
import Interact._
Free.runFC(interactScript)(InteractConsole)
}
What's your first name?
Tiger
What's your last name?
Chan
Hello Tiger Chan, nice to meet you!
type InteractMapTester[A] = Map[String,String] => (List[String], A)
implicit val mapTesterMonad = new Monad[InteractMapTester] {
def point[A](a: => A) = _ => (List(), a)
def bind[A,B](ia: InteractMapTester[A])(f: A => InteractMapTester[B]): InteractMapTester[B] =
m => {
val (o1,a1) = ia(m)
val (o2,a2) = f(a1)(m)
(o1 ++ o2, a2)
}
}
object InteractTesterMap extends (Interact ~> InteractMapTester) {
def apply[A](ia: Interact[A]): InteractMapTester[A] = ia match {
case Ask(p) => { m => (List(), m(p)) } //m(p)返回提问对应的答案作为键盘输入
case Tell(s) => { m => (List(s), ()) } //List(s)在bind函数中的o1++o2形成跟踪记录
//在运算AST时就会调用InteractMapTester的bind函数
}
}
object freePrgDemo extends App {
import FreeModules._
import FreeInteract._
import Interact._
//Free.runFC(interactScript)(InteractConsole)
val result = Free.runFC(interactScript)(InteractTesterMap).apply(
Map(
"What's your first name?" -> "tiger",
"What's your last name?" -> "chan"
))
println(result)
}
//产生以下输出结果
(List(Hello tiger chan, nice to meet you!),())
从mapTesterMonad定义中的bind看到了这句:o1++o2,是Logger的典型特征。那么用Writer能不能实现同等效果呢?我们先看看WriterT:
final case class WriterT[F[_], W, A](run: F[(W, A)]) { self =>
...
def flatMap[B](f: A => WriterT[F, W, B])(implicit F: Bind[F], s: Semigroup[W]): WriterT[F, W, B] =
flatMapF(f.andThen(_.run))
def flatMapF[B](f: A => F[(W, B)])(implicit F: Bind[F], s: Semigroup[W]): WriterT[F, W, B] =
writerT(F.bind(run){wa =>
val z = f(wa._2)
F.map(z)(wb => (s.append(wa._1, wb._1), wb._2))
})
type WriterTF[A] = Map[String,String] => A
type InteractWriterTester[A] = WriterT[WriterTF,List[String],A]
以下是用WriterT实现的Interpreter版本:
type WriterTF[A] = Map[String,String] => A
type InteractWriterTester[A] = WriterT[WriterTF,List[String],A]
def testerToWriter[A](f: Map[String,String] => (List[String], A)) =
WriterT[WriterTF,List[String],A](f)
implicit val writerTesterMonad = WriterT.writerTMonad[WriterTF, List[String]]
object InteractTesterWriter extends (Interact ~> InteractWriterTester) {
def apply[A](ia: Interact[A]): InteractWriterTester[A] = ia match {
case Ask(p) => testerToWriter { m => (List(), m(p)) }
case Tell(s) => testerToWriter { m => (List(s), ())}
}
}
object freePrgDemo extends App {
import FreeModules._
import FreeInteract._
import Interact._
//Free.runFC(interactScript)(InteractConsole)
//val result = Free.runFC(interactScript)(InteractTesterMap).apply(
val result = Free.runFC(interactScript)(InteractTesterWriter).run(
Map(
"What's your first name?" -> "tiger",
"What's your last name?" -> "chan"
))
println(result)
}
我们再设计另一个用户登录Login的例子:
object FreeUserLogin {
import Dependencies._
trait UserLogin[+A]
type FreeUserLogin[A] = Free.FreeC[UserLogin,A]
object UserLogin {
case class Login(user: String, pswd: String) extends UserLogin[Boolean]
implicit def loginToFree[A](ul: UserLogin[A]) = Free.liftFC(ul)
type LoginService[A] = Reader[PasswordControl,A]
object LoginInterpreter extends (UserLogin ~> LoginService) {
def apply[A](ul: UserLogin[A]): LoginService[A] = ul match {
case Login(u,p) => Reader( cr => cr.matchPassword(u, p))
}
}
}
import UserLogin._
val loginScript = for {
b <- Login("Tiger","1234")
} yield b
}
object Dependencies {
trait PasswordControl {
type User = String
type Password = String
val pswdMap: Map[User, Password]
def matchPassword(u: User, p: Password): Boolean
}
}
import Dependencies._
import FreeUserLogin._
import UserLogin._
object Passwords extends PasswordControl { //依赖实例
val pswdMap = Map (
"Tiger" -> "1234",
"John" -> "0332"
)
def matchPassword(u: User, p: Password) = pswdMap.getOrElse(u, p+"!") === p
}
val result = Free.runFC(loginScript)(LoginInterpreter).run(Passwords) //注入依赖
println(result)
不过即使能够运行,loginScsript的功能明显不完整,还需要像Interact那样的互动部分来获取用户输入信息。那么我们是不是考虑在ADT层次上把Interact和UserLogin合并起来,像这样:
case class Ask(prompt: String) extends Interact[String]
case class Tell(msg: String) extends Interact[Unit]
case class Login(user: String, pswd: String) extends Interact[Boolean]
val interLogin: Free[???, A] = for {
user <- Ask("Enter User ID:") //Free[Interact,A]
pswd <- Ask("Enter Password:") //Free[Interact,A]
ok <- Login(user,pswd) //Free[UserLogin,A]
} yield ok
/** `F` on the left, and `G` on the right, of [[scalaz.\/]].
*
* @param run The underlying [[scalaz.\/]]. */
final case class Coproduct[F[_], G[_], A](run: F[A] \/ G[A]) {
import Coproduct._
def map[B](f: A => B)(implicit F: Functor[F], G: Functor[G]): Coproduct[F, G, B] =
Coproduct(run.bimap(F.map(_)(f), G.map(_)(f)))
...
从run:F[A]\/G[A]可以理解Coproduct是两种语句F,G的联合(union)。在我们上面的例子里我们可以用下面的表达方式代表Interact和UserLogin两种语句的联合(union):
type InteractLogin[A] = Coproduct[Interact,UserLogin,A]
这是一个语义更广泛的类型:包含了Interact和UserLogin语义。我们可以用Inject类型来把Interact和UserLogin语句集“注入”到一个更大的句集。Inject是这样定义的:scalaz/Inject.scala
/**
* Inject type class as described in "Data types a la carte" (Swierstra 2008).
*
* @see [[http://www.staff.science.uu.nl/~swier004/Publications/DataTypesALaCarte.pdf]]
*/
sealed abstract class Inject[F[_], G[_]] {
def inj[A](fa: F[A]): G[A]
def prj[A](ga: G[A]): Option[F[A]]
}
sealed abstract class InjectInstances {
implicit def reflexiveInjectInstance[F[_]] =
new Inject[F, F] {
def inj[A](fa: F[A]) = fa
def prj[A](ga: F[A]) = some(ga)
}
implicit def leftInjectInstance[F[_], G[_]] =
new Inject[F, ({type λ[α] = Coproduct[F, G, α]})#λ] {
def inj[A](fa: F[A]) = Coproduct.leftc(fa)
def prj[A](ga: Coproduct[F, G, A]) = ga.run.fold(some(_), _ => none)
}
implicit def rightInjectInstance[F[_], G[_], H[_]](implicit I: Inject[F, G]) =
new Inject[F, ({type λ[α] = Coproduct[H, G, α]})#λ] {
def inj[A](fa: F[A]) = Coproduct.rightc(I.inj(fa))
def prj[A](ga: Coproduct[H, G, A]) = ga.run.fold(_ => none, I.prj(_))
}
}
...
1、reflexiceInjectInstance[F[_]]:自我注入
2、leftInjectInstance[F[_],G[_]]:把F[A]注入Coproduct[F,G,A]的left(-\/)
3、rightInjectInstance[F[_],G[_],H[_]]:把F[A]注入Coproduct的right(\/-)。需要先把F注入G(inj(F[A]):G[A])
我们可以用implicitly来证明Interact和UserLogin的Inject实例存在:
val selfInj = implicitly[Inject[Interact,Interact]]
type LeftInterLogin[A] = Coproduct[Interact,UserLogin,A]
val leftInj = implicitly[Inject[Interact,LeftInterLogin]]
type RightInterLogin[A] = Coproduct[UserLogin,LeftInterLogin,A]
val rightInj = implicitly[Inject[Interact,RightInterLogin]]
现在我们需要把Coproduct[F,G,A]的F与G合并然后把F[A]升格成Free[G,A]:
object coproduct {
def lift[F[_],G[_],A](fa: F[A])(implicit I: Inject[F,G]): Free.FreeC[G,A] = Free.liftFC(I.inj(fa))
}
object coproduct {
import FreeInteract._
import Interact._
import FreeUserLogin._
import UserLogin._
def lift[F[_],G[_],A](fa: F[A])(implicit I: Inject[F,G]): Free.FreeC[G,A] = Free.liftFC(I.inj(fa))
class Interacts[G[_]](implicit I: Inject[Interact,G]) {
def ask(prompt: String): Free.FreeC[G,String] = lift(Ask(prompt))
def tell(msg: String): Free.FreeC[G,Unit] = lift(Tell(msg))
}
class Logins[G[_]](implicit I: Inject[UserLogin,G]) {
def login(u: String, p: String): Free.FreeC[G,Boolean] = lift(Login(u,p))
}
}
我们用lift把基础Interact和UserLogin的语句注入了联合的语句集G[A],然后升格成FreeC[G,A]。现在我们可以把Interact,UserLogin这两种语句用在同一个for-comprehension里了:
def loginScript[G[_]](implicit I: Interacts[G], L: Logins[G]) ={
import I._
import L._
for {
uid <- ask("ya id?")
pwd <- ask("password?")
login <- login(uid,pwd)
_ <- if (login) tell("ya lucky bastard!") else tell("geda fk outa here!")
} yield()
}
有了Inject和Lift,现在已经成功的用两种ADT集成了一个AST。不过我们还必须提供Interacts[G]和Logins[G]实例:
object CoproductModules {
object CoproductFunctions {
import FreeInteract._
import Interact._
import FreeUserLogin._
import UserLogin._
def lift[F[_],G[_],A](fa: F[A])(implicit I: Inject[F,G]): Free.FreeC[G,A] = Free.liftFC(I.inj(fa))
class Interacts[G[_]](implicit I: Inject[Interact,G]) {
def ask(prompt: String): Free.FreeC[G,String] = lift(Ask(prompt))
def tell(msg: String): Free.FreeC[G,Unit] = lift(Tell(msg))
}
object Interacts {
implicit def instance[G[_]](implicit I: Inject[Interact,G]) = new Interacts[G]
}
class Logins[G[_]](implicit I: Inject[UserLogin,G]) {
def login(u: String, p: String): Free.FreeC[G,Boolean] = lift(Login(u,p))
}
object Logins {
implicit def instance[G[_]](implicit I: Inject[UserLogin,G]) = new Logins[G]
}
}
现在我们的语句集(AST)是一个联合的语句集(Coproduct)。那么,我们应该怎么去运算它呢?我们应该如何实现它的Interpreter?现在我们面对的Monadic程序类型是个Coproduct:
type InteractLogin[A] = Coproduct[Interact,UserLogin,A]
val loginPrg = loginScript[InteractLogin]
def or[F[_],G[_],H[_]](fg: F ~> G, hg: H ~> G): ({type l[x] = Coproduct[F,H,x]})#l ~> G =
new (({type l[x] = Coproduct[F,H,x]})#l ~> G) {
def apply[A](ca: Coproduct[F,H,A]): G[A] = ca.run match {
case -\/(fa) => fg(fa)
case \/-(ha) => hg(ha)
}
}
object InteractReader extends (Interact ~> LoginService) {
def apply[A](ia: Interact[A]): LoginService[A] = ia match {
case Ask(p) => println(p); Reader(cr => readLine)
case Tell(m) => println(m); Reader(cr => ())
}
}
object freePrgDemo extends App {
import FreeModules._
import FreeInteract._
import Interact._
//Free.runFC(interactScript)(InteractConsole)
//val result = Free.runFC(interactScript)(InteractTesterMap).apply(
/* val result = Free.runFC(interactScript)(InteractTesterWriter).run(
Map(
"What's your first name?" -> "tiger",
"What's your last name?" -> "chan"
))
println(result)
*/
import Dependencies._
import FreeUserLogin._
import UserLogin._
object Passwords extends PasswordControl {
val pswdMap = Map (
"Tiger" -> "1234",
"John" -> "0332"
)
def matchPassword(u: User, p: Password) = pswdMap.getOrElse(u, p+"!") === p
}
/*
val result = Free.runFC(loginScript)(LoginInterpreter).run(Passwords)
println(result)
*/
import CoproductDemo._
Free.runFC(loginPrg)(or(InteractReader,LoginInterpreter)).run(Passwords)
}
我们把密码管理依赖也注入进去了。看看结果:
ya id?
Tiger
password?
2012
geda fk outa here!
ya id?
Tiger
password?
1234
ya lucky bastard!
ya id?
John
password?
0332
ya lucky bastard!
OK, 把这节示范源代码提供在下面:
package demos
import scalaz._
import Scalaz._
import scala.language.higherKinds
import scala.language.implicitConversions
object FreeModules {
object FreeInteract {
trait Interact[+A]
type FreeInteract[A] = Free.FreeC[Interact,A]
object Interact {
case class Ask(prompt: String) extends Interact[String]
case class Tell(msg: String) extends Interact[Unit]
implicit def interactToFreeC[A](ia: Interact[A]) = Free.liftFC(ia)
object InteractConsole extends (Interact ~> Id) {
def apply[A](ia: Interact[A]): Id[A] = ia match {
case Ask(p) => println(p); readLine
case Tell(m) => println(m)
}
}
type InteractMapTester[A] = Map[String,String] => (List[String], A)
implicit val mapTesterMonad = new Monad[InteractMapTester] {
def point[A](a: => A) = _ => (List(), a)
def bind[A,B](ia: InteractMapTester[A])(f: A => InteractMapTester[B]): InteractMapTester[B] =
m => {
val (o1,a1) = ia(m)
val (o2,a2) = f(a1)(m)
(o1 ++ o2, a2)
}
}
object InteractTesterMap extends (Interact ~> InteractMapTester) {
def apply[A](ia: Interact[A]): InteractMapTester[A] = ia match {
case Ask(p) => { m => (List(), m(p)) } //m(p)返回提问对应的答案作为键盘输入
case Tell(s) => { m => (List(s), ()) } //List(s)在bind函数中的o1++o2形成跟踪记录
//在运算AST时会用到InteractMapTester的bind
}
}
type WriterTF[A] = Map[String,String] => A
type InteractWriterTester[A] = WriterT[WriterTF,List[String],A]
def testerToWriter[A](f: Map[String,String] => (List[String], A)) =
WriterT[WriterTF,List[String],A](f)
implicit val writerTesterMonad = WriterT.writerTMonad[WriterTF, List[String]]
object InteractTesterWriter extends (Interact ~> InteractWriterTester) {
def apply[A](ia: Interact[A]): InteractWriterTester[A] = ia match {
case Ask(p) => testerToWriter { m => (List(), m(p)) }
case Tell(s) => testerToWriter { m => (List(s), ())}
}
}
}
import Interact._
val interactScript = for {
first <- Ask("What's your first name?")
last <- Ask("What's your last name?")
_ <- Tell(s"Hello ${first} ${last}, nice to meet you!")
} yield ()
}
object FreeUserLogin {
import Dependencies._
trait UserLogin[+A]
type FreeUserLogin[A] = Free.FreeC[UserLogin,A]
object UserLogin {
case class Login(user: String, pswd: String) extends UserLogin[Boolean]
implicit def loginToFree[A](ul: UserLogin[A]) = Free.liftFC(ul)
type LoginService[A] = Reader[PasswordControl,A]
object LoginInterpreter extends (UserLogin ~> LoginService) {
def apply[A](ul: UserLogin[A]): LoginService[A] = ul match {
case Login(u,p) => Reader( cr => cr.matchPassword(u, p))
}
}
}
import UserLogin._
val loginScript = for {
b <- Login("Tiger","1234")
} yield b
}
}
object Dependencies {
trait PasswordControl {
type User = String
type Password = String
val pswdMap: Map[User, Password]
def matchPassword(u: User, p: Password): Boolean
}
}
object CoproductDemo {
import FreeModules._
import FreeUserLogin._
import UserLogin._
import FreeInteract._
import Interact._
import Dependencies._
def lift[F[_],G[_],A](fa: F[A])(implicit I: Inject[F,G]): Free.FreeC[G,A] = Free.liftFC(I.inj(fa))
class Interacts[G[_]](implicit I: Inject[Interact,G]) {
def ask(prompt: String) = lift(Ask(prompt))
def tell(msg: String) = lift(Tell(msg))
}
object Interacts {
implicit def instance[F[_]](implicit I: Inject[Interact,F]) = new Interacts[F]
}
class Logins[G[_]](implicit I: Inject[UserLogin,G]) {
def login(user: String, pswd: String) = lift(Login(user,pswd))
}
object Logins {
implicit def instance[F[_]](implicit I: Inject[UserLogin,F]) = new Logins[F]
}
def loginScript[G[_]](implicit I: Interacts[G], L: Logins[G]) ={
import I._
import L._
for {
uid <- ask("ya id?")
pwd <- ask("password?")
login <- login(uid,pwd)
_ <- if (login) tell("ya lucky bastard!") else tell("geda fk outa here!")
} yield()
}
def or[F[_],G[_],H[_]](fg: F ~> G, hg: H ~> G): ({type l[x] = Coproduct[F,H,x]})#l ~> G =
new (({type l[x] = Coproduct[F,H,x]})#l ~> G) {
def apply[A](ca: Coproduct[F,H,A]): G[A] = ca.run match {
case -\/(fa) => fg(fa)
case \/-(ha) => hg(ha)
}
}
type InteractLogin[A] = Coproduct[Interact,UserLogin,A]
val loginPrg = loginScript[InteractLogin]
object InteractReader extends (Interact ~> LoginService) {
def apply[A](ia: Interact[A]): LoginService[A] = ia match {
case Ask(p) => println(p); Reader(cr => readLine)
case Tell(m) => println(m); Reader(cr => ())
}
}
}
object freePrgDemo extends App {
import FreeModules._
import FreeInteract._
import Interact._
//Free.runFC(interactScript)(InteractConsole)
//val result = Free.runFC(interactScript)(InteractTesterMap).apply(
/* val result = Free.runFC(interactScript)(InteractTesterWriter).run(
Map(
"What's your first name?" -> "tiger",
"What's your last name?" -> "chan"
))
println(result)
*/
import Dependencies._
import FreeUserLogin._
import UserLogin._
object Passwords extends PasswordControl {
val pswdMap = Map (
"Tiger" -> "1234",
"John" -> "0332"
)
def matchPassword(u: User, p: Password) = pswdMap.getOrElse(u, p+"!") === p
}
/*
val result = Free.runFC(loginScript)(LoginInterpreter).run(Passwords)
println(result)
*/
import CoproductDemo._
Free.runFC(loginPrg)(or(InteractReader,LoginInterpreter)).run(Passwords)
}