package.scala:
object State extends StateFunctions {
def apply[S, A](f: S => (S, A)): State[S, A] = new StateT[Id, S, A] {
def apply(s: S) = f(s)
}
}
def state1 = State[Int,String](i => (i + 1, "str"))
状態として 1を足して、 値に str を持つ。
State[S,A] S が状態、Aが値である。
-
run 状態と値を返す 例 (1,"str")
-
exec 状態を返す 例 1
-
eval 値を返す 例 str
-
init init[S]: State[S, S]
-
modify modify[S](f: S => S):
val test1 = for {
a <- init[Int]
_ <- modify[Int]{ i => (i + 1) * 3 }
b <- init[Int]
} yield b
test eval 1 を実行した場合
a <- init[Int]
-> (状態,値)は(1,1)となるmodify[Int]{ i => (i + 1) * 3 }
-> (6,1) となるb <- init[Int]
-> (6,6) となる
scala> test1 eval 1
res54: scalaz.Id.Id[Int] = 6
val test2 = for {
a <- init[Int]
_ <- modify[Int]{ i => (i + 1) * 3 }
_ <- init[Int]
b <-gets[Int,Option[Int]](Option(_))
} yield b
scala> test2 run 1
res55: (Int, Option[Int]) = (6,Some(6))
-
!
scalaz 6 のソースでは apply(s)._2
値のほうである -> eval と一緒 -
~>
scalaz 6 のソースでは apply(s)._1
ステートのほう -> exec と一緒