Skip to content

Instantly share code, notes, and snippets.

@takungsk
Last active December 10, 2015 01:18
Show Gist options
  • Save takungsk/4357066 to your computer and use it in GitHub Desktop.
Save takungsk/4357066 to your computer and use it in GitHub Desktop.

State Monad in Scalaz

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)
    }
  }

State の例

def state1 = State[Int,String](i => (i + 1, "str"))

状態として 1を足して、 値に str を持つ。

State[S,A]

State[S,A] S が状態、Aが値である。

ヘルパー関数

  • run 状態と値を返す 例 (1,"str")

  • exec 状態を返す 例 1

  • eval 値を返す 例 str

  • init init[S]: State[S, S]

  • modify modify[S](f: S => S):

sample1

val test1 = for {
  a <- init[Int]
  _ <- modify[Int]{ i => (i + 1) * 3 }
  b <- init[Int]
} yield b

結果

test eval 1 を実行した場合

  1. a <- init[Int] -> (状態,値)は(1,1)となる
  2. modify[Int]{ i => (i + 1) * 3 } -> (6,1) となる
  3. b <- init[Int] -> (6,6) となる
scala> test1 eval 1
res54: scalaz.Id.Id[Int] = 6

sample2

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 のサンプルで出ている ! と ~> について

  • !
    scalaz 6 のソースでは apply(s)._2
    値のほうである -> eval と一緒

  • ~>
    scalaz 6 のソースでは apply(s)._1
    ステートのほう -> exec と一緒

参考情報

  1. Scalaz state monad examples
  2. 独習 Scalaz: 7日目
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment