Search code examples
scalastatemonadsscalazlenses

Scala (scalaz) State monad - map over Option state type


How can I apply implement the following function?

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

The bigger picture is this:

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

Is there nicer way to deal with Option properties?


Solution

  • One way to create the wrapIntoOption function would be to call run on the passed State[S, A] and convert the resulting (S, A) tuple into (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)
      })
    

    You could then define setEngineOptCylinders as :

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

    Which you can use as :

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