0
0
0
1. 云栖社区>
2. 博客>
3. 正文

``````/*
val a = e1
val b = e2(a)
val c = e3(a,b)
val d = e2(c)
*/``````

``````import scalaz._
import Scalaz._
def e1:Id[Int] = 10                               //> e1: => scalaz.Scalaz.Id[Int]
def e2(a: Int): Id[Int] = a + 1                   //> e2: (a: Int)scalaz.Scalaz.Id[Int]
def e3(a: Int, b: Int): Id[Int] = a + b           //> e3: (a: Int, b: Int)scalaz.Scalaz.Id[Int]
for {
a <- e1
b <- e2(a)
c <- e3(a,b)
d <- e2(c)
} yield d                                         //> res0: scalaz.Scalaz.Id[Int] = 22``````

``````import scalaz._
import Scalaz._
def e1:Option[Int] = 10.some                      //> e1: => Option[Int]
def e2(a: Int): Option[Int] = (a + 1).some        //> e2: (a: Int)Option[Int]
def e3(a: Int, b: Int): Option[Int] = (a + b).some//> e3: (a: Int, b: Int)Option[Int]
for {
a <- e1
b <- e2(a)
c <- e3(a,b)
d <- e2(c)
} yield d                                         //> res0: Option[Int] = Some(22)``````

``````import scalaz._
import Scalaz._
//> e3: (a: Int, b: Int)scalaz.Reader[Int,Int]
val prg = for {
a <- e1
b <- e2(a)
c <- e3(a,b)
d <- e2(c)
} yield d                                         //> prg  : scalaz.Kleisli[scalaz.Id.Id,Int,Int] = Kleisli(<function1>)
prg.run(10)                                       //> res0: scalaz.Id.Id[Int] = 22``````

``case class StateT[F[_],S,A](run: S => F[(S,A)])``

``````for {
a <- 3.some
b <- (None: Option[Int])
c <- 4.some
} yield c                                         //> res1: Option[Int] = None
val statePrg = for {
a <- get[Int]
b <- State[Int,Int](s => (s, s + a))
_ <- put(9)
} yield b                                         //> statePrg  : scalaz.IndexedStateT[scalaz.Id.Id,Int,Int,Int] = scalaz.IndexedS
//| tateT\$\$anon\$10@15ff3e9e
statePrg.run(3)                                   //> res2: scalaz.Id.Id[(Int, Int)] = (9,6)``````

``````case class OptionState[S,A](run: S => Option[(S,A)]) {
def map[B](f: A => B): OptionState[S,B] =
OptionState {
s => run(s) map { case (s1,a1) => (s1,f(a1)) }
}
def flatMap[B](f: A => OptionState[S,B]): OptionState[S,B] =
OptionState {
s => run(s) flatMap { case (s1,a1) => f(a1).run(s1) }
}
}``````

`````` def liftOption[S,A](oa: Option[A]): OptionState[S,A] = oa match {
case Some(a) => OptionState {s => (s,a).some }
case None => OptionState {_ => none}
}
def liftState[S,A](sa: State[S,A]): OptionState[S,A] =
OptionState {s => sa(s).some}``````

``````val osprg: OptionState[Int,Int] = for {
a <- liftOption(3.some)
b <- liftState(put(a))
c <- liftState(get[Int])
d <- liftState(State[Int,Int](s => (s+c, s+a)))
} yield c                                        //> osprg  : Exercises.rws.OptionState[Int,Int] = OptionState(<function1>)
osprg.run(2)                                     //> res3: Option[(Int, Int)] = Some((6,3))
val osprg1: OptionState[Int,Int] = for {
a <- liftOption(3.some)
b <- liftState(put(a))
_ <- liftOption((None: Option[Int]))
c <- liftState(get[Int])
d <- liftState(State[Int,Int](s => (s+c, s+a)))
} yield c                                        //> osprg1  : Exercises.rws.OptionState[Int,Int] = OptionState(<function1>)
osprg1.run(2)                                    //> res4: Option[(Int, Int)] = None``````

``````type ReaderWriterStateT[F[_], -R, W, S, A] = IndexedReaderWriterStateT[F, R, W, S, S, A]
def apply[F[_], R, W, S, A](f: (R, S) => F[(W, A, S)]): ReaderWriterStateT[F, R, W, S, A] = IndexedReaderWriterStateT[F, R, W, S, S, A] { (r: R, s: S) => f(r, s) }
}
type IndexedReaderWriterState[-R, W, -S1, S2, A] = IndexedReaderWriterStateT[Id, R, W, S1, S2, A]
def apply[R, W, S1, S2, A](f: (R, S1) => (W, A, S2)): IndexedReaderWriterState[R, W, S1, S2, A] = IndexedReaderWriterStateT[Id, R, W, S1, S2, A] { (r: R, s: S1) => f(r, s) }
}
def apply[R, W, S, A](f: (R, S) => (W, A, S)): ReaderWriterState[R, W, S, A] = IndexedReaderWriterStateT[Id, R, W, S, S, A] { (r: R, s: S) => f(r, s) }
}
type IRWST[F[_], -R, W, -S1, S2, A] = IndexedReaderWriterStateT[F, R, W, S1, S2, A]
type IRWS[-R, W, -S1, S2, A] = IndexedReaderWriterState[R, W, S1, S2, A]
type RWST[F[_], -R, W, S, A] = ReaderWriterStateT[F, R, W, S, A]
type RWS[-R, W, S, A] = ReaderWriterState[R, W, S, A]

``````case class Reader[R, A](f: R => A)     //传入R，返回A后不理会R
case class Writer[W, A](w: (W, A))     //直接返回W,A
case class State[S, A](f: S => (A, S)) //传入S, 返回A和S``````

``````case class ReaderWriterState[R, W, S, A](
run: (R, S) => (W, A, S)  //传入R,S 返回W,A,S
)
case class ReaderWriterStateT[F[_],R, W, S, A](
run: (R, S) => F[(W, A, S)]  //传入R,S 返回W,A,S。只是包在了F内
) ``````

``````/** A monad transformer stack yielding `(R, S1) => F[(W, A, S2)]`. */
sealed abstract class IndexedReaderWriterStateT[F[_], -R, W, -S1, S2, A] {
self =>
def run(r: R, s: S1): F[(W, A, S2)]

/** Discards the writer component. */
def state(r: R)(implicit F: Functor[F]): IndexedStateT[F, S1, S2, A] =
IndexedStateT((s: S1) => F.map(run(r, s)) {
case (w, a, s1) => (s1, a)
})

/** Calls `run` using `Monoid[S].zero` as the initial state */
def runZero[S <: S1](r: R)(implicit S: Monoid[S]): F[(W, A, S2)] =
run(r, S.zero)

/** Run, discard the final state, and return the final value in the context of `F` */
def eval(r: R, s: S1)(implicit F: Functor[F]): F[(W, A)] =
F.map(run(r,s)) { case (w,a,s2) => (w,a) }

/** Calls `eval` using `Monoid[S].zero` as the initial state */
def evalZero[S <: S1](r:R)(implicit F: Functor[F], S: Monoid[S]): F[(W,A)] =
eval(r,S.zero)

/** Run, discard the final value, and return the final state in the context of `F` */
def exec(r: R, s: S1)(implicit F: Functor[F]): F[(W,S2)] =
F.map(run(r,s)){case (w,a,s2) => (w,s2)}

/** Calls `exec` using `Monoid[S].zero` as the initial state */
def execZero[S <: S1](r:R)(implicit F: Functor[F], S: Monoid[S]): F[(W,S2)] =
exec(r,S.zero)
...``````

``````def map[B](f: A => B)(implicit F: Functor[F]): IndexedStateT[F, S1, S2, B] = IndexedStateT(s => F.map(apply(s)) {
case (s1, a) => (s1, f(a))
})
def flatMap[S3, B](f: A => IndexedStateT[F, S2, S3, B])(implicit F: Bind[F]): IndexedStateT[F, S1, S3, B] = IndexedStateT(s => F.bind(apply(s)) {
case (s1, a) => f(a)(s1)
})``````

``````private trait ReaderWriterStateTMonad[F[_], R, W, S]
with IndexedReaderWriterStateTFunctor[F, R, W, S, S] {
implicit def W: Monoid[W]

def bind[A, B](fa: ReaderWriterStateT[F, R, W, S, A])(f: A => ReaderWriterStateT[F, R, W, S, B]): ReaderWriterStateT[F, R, W, S, B] = fa flatMap f
def point[A](a: => A): ReaderWriterStateT[F, R, W, S, A] =
ReaderWriterStateT((_, s) => F.point((W.zero, a, s)))
ReaderWriterStateT((r, s) => F.point((W.zero, r, s)))
def local[A](f: R => R)(fa: ReaderWriterStateT[F, R, W, S, A]): ReaderWriterStateT[F, R, W, S, A] =
override def scope[A](k: R)(fa: ReaderWriterStateT[F, R, W, S, A]): ReaderWriterStateT[F, R, W, S, A] =
override def asks[A](f: R => A): ReaderWriterStateT[F, R, W, S, A] =
ReaderWriterStateT((r, s) => F.point((W.zero, f(r), s)))
def init: ReaderWriterStateT[F, R, W, S, S] =
ReaderWriterStateT((_, s) => F.point((W.zero, s, s)))
def get = init
def put(s: S): ReaderWriterStateT[F, R, W, S, Unit] =
ReaderWriterStateT((r, _) => F.point((W.zero, (), s)))
override def modify(f: S => S): ReaderWriterStateT[F, R, W, S, Unit] =
ReaderWriterStateT((r, s) => F.point((W.zero, (), f(s))))
override def gets[A](f: S => A): ReaderWriterStateT[F, R, W, S, A] =
ReaderWriterStateT((_, s) => F.point((W.zero, f(s), s)))
def writer[A](w: W, v: A): ReaderWriterStateT[F, R, W, S, A] =
ReaderWriterStateT((_, s) => F.point((w, v, s)))
override def tell(w: W): ReaderWriterStateT[F, R, W, S, Unit] =
ReaderWriterStateT((_, s) => F.point((w, (), s)))
def listen[A](ma: ReaderWriterStateT[F, R, W, S, A]): ReaderWriterStateT[F, R, W, S, (A, W)] =
ReaderWriterStateT((r, s) => F.map(ma.run(r, s)) { case (w, a, s1) => (w, (a, w), s1)})
}``````

``````val program: ReaderWriterState[Config, List[String], Int, Int] = for {
_   <- log("Start - r: %s, s: %s")
res <- invokeService
_   <- log("Between - r: %s, s: %s")
_   <- setService(8,"Com8")
_   <- invokeService
_   <- log("Done - r: %s, s: %s")
} yield res      //> program  : scalaz.RWS[Exercises.rws.Config,List[String],Int,Int] = scalaz.I

``````case class Config(var port: Int, var portName: String)
def log[R, S](msg: String): RWS[R, List[String], S, Unit] =
case (r, s) => (msg.format(r, s) :: Nil, (), s) //.point[Identity]
}                                             //> log: [R, S](msg: String)scalaz.RWS[R,List[String],S,Unit]
def invokeService: ReaderWriterState[Config, List[String], Int, Int] =
case (cfg, invocationCount) => (
List("Invoking service with port: " + cfg.portName),
scala.util.Random.nextInt(100),
invocationCount + 1
) //.point[Identity]
//| ],Int,Int]
def setService(p: Int, n: String): ReaderWriterState[Config, List[String], Int, Int] =
case (cfg, invocationCount) => cfg.port=p; cfg.portName=n
(List("Changing service port to " + cfg.portName),
scala.util.Random.nextInt(100),
invocationCount)
}                                             //> setService: (p: Int, n: String)scalaz.ReaderWriterState[Exercises.rws.Confi
//| g,List[String],Int,Int]

val program: ReaderWriterState[Config, List[String], Int, Int] = for {
_   <- log("Start - r: %s, s: %s")
res <- invokeService
_   <- log("Between - r: %s, s: %s")
_   <- setService(8,"Com8")
_   <- invokeService
_   <- log("Done - r: %s, s: %s")
} yield res                                     //> program  : scalaz.RWS[Exercises.rws.Config,List[String],Int,Int] = scalaz.I
val r =   program run (Config(443,"Com3"), 0)     //> r  : scalaz.Id.Id[(List[String], Int, Int)] = (List(Start - r: Config(443,C
//| om3), s: 0, Invoking service with port: Com3, Between - r: Config(443,Com3)
//| , s: 1, Changing service port to Com8, Invoking service with port: Com8, Do
//| ne - r: Config(88,Com8), s: 2),68,2)
println("Result: " + r._2)                        //> Result: 68
println("Service invocations: " + r._3)           //> Service invocations: 2
println("Log: %n%s".format(r._1.mkString("\t", "%n\t".format(), "")))
//> Log:
//|     Start - r: Config(443,Com3), s: 0
//|     Invoking service with port: Com3
//|     Between - r: Config(443,Com3), s: 1
//|     Changing service port to Com8
//|     Invoking service with port: Com8
//|     Done - r: Config(88,Com8), s: 2``````

+ 关注

corcosa 16014人浏览