Scala(scalaz)状态monad - 映射选项状态类型

时间:2015-12-25 09:55:35

标签: scala state monads scalaz lens

如何应用实现以下功能?

def wrapIntoOption(state: State[S, A]): State[Option[S], Option[A]]

更大的图景是:

case class Engine(cylinders: Int)
case class Car(engineOpt: Option[Engine])

val engineOptLens = Lens.lensu((c, e) => c.copy(engineOpt = e), _.engineOpt)

def setEngineCylinders(count: Int): State[Engine, Int] = State { engine =>
  (engine.copy(cylinders = count), engine.cylinders)
}

def setEngineOptCylinders(count: Int): State[Option[Engine], Option[Int]] = {
  ??? // how to reuse setEngineCylinders?
}

def setCarCylinders(count: Int): State[Car, Option[Int]] = {
  engineOptLens.lifts(setEngineOptCylinders)
}

有没有更好的方法来处理Option属性?

1 个答案:

答案 0 :(得分:1)

创建wrapIntoOption函数的一种方法是在传递的run上调用State[S, A],并将生成的(S, A)元组转换为(Option[S], Option[A])

import scalaz.State
import scalaz.std.option._
import scalaz.syntax.std.option._

def wrapIntoOption[S, A](state: State[S, A]): State[Option[S], Option[A]] =
  State(_.fold((none[S], none[A])){ oldState =>
    val (newState, result) = state.run(oldState)
    (newState.some, result.some)
  })

然后,您可以将setEngineOptCylinders定义为:

def setEngineOptCylinders(count: Int): State[Option[Engine], Option[Int]] = 
  wrapIntoOption(setEngineCylinders(count))

您可以将其用作:

scala> val (newEngine, oldCylinders) = setEngineOptCylinders(8).run(Engine(6).some)
newEngine: Option[Engine] = Some(Engine(8))
oldCylinders: Option[Int] = Some(6)