Map `State` via `Lens`

220 Views Asked by At

Is there some function with signature like

lensMapState[S, T, A](lens : Lens[S, T]): State[T, A] => State[S, A]

With semantics run modification of chosen part and get result

One implementation could be

def lensMapState[S, T, A](lens: Lens[S, T]): State[T, A] => State[S, A] =
    stateT => State { s =>
      val (result, x) = stateT.run(lens.get(s))
      (lens.set(result)(s), x)
    } 

but if there more straightforward way using monocle or scalaz.Lens ?

1

There are 1 best solutions below

3
On

I think what you are looking for is something like this:

import scalaz._
import Scalaz._

case class Person(name: String, age: Int)
case object Person {
  val _age = Lens.lensu[Person, Int]((p, a) => p.copy(age = a), _.age 
}

val state = for {
  a <- Person._age %= { _ + 1 } 
} yield a

state.run(Person("Holmes", 42))

which results in

res0: scalaz.Id.Id[(Person, Int)] = (Person(Holmes,43),43)

There are many lens/state related functions defined in https://github.com/scalaz/scalaz/blob/series/7.1.x/core/src/main/scala/scalaz/Lens.scala Monocle follows a similiar principle. The related functions are defined in monocle.state as far as I know.