Scalaz Lens 到 ReaderWriterState

Scalaz Lens to ReaderWriterState

给定,说

case class Person(age: Int)
val ageL: Lens[Person, Int] = ...

我怎么想出来的:

def incrementAge(by: Int): ReaderWriterState[Config, String, Person]

同时利用 ageL 镜头。 Scalaz Lens 有一些实用程序可以从 Lens 中创建 State,但我不确定如何将其转换为 ReaderWriterState

你可以在镜头上使用mods方法,在结果状态上使用rwst来写得非常清楚:

import scalaz._, Scalaz._

type Config = Map[String, String]

case class Person(age: Int)
val ageL: Lens[Person, Int] = Lens.lensu(_ copy _, _.age)

def incrementAge(by: Int): ReaderWriterState[Config, String, Person, Int] =
  ageL.mods(_ + by).rwst[String, Config]

然后:

scala> incrementAge(1).run(Map.empty, Person(20))
res0: scalaz.Id.Id[(String, Int, Person)] = ("",21,Person(21))

这将 return 增加年龄,这似乎是一件合理的事情,但如果您只关心状态的变化,则可以使用 ageL.mods_(_ + by) 丢弃该值。