给定,说
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))
这将返回增加的年龄,这似乎是一个合理的事情,但如果您只关心状态的更改,您可以使用 ageL.mods_(_ + by)< 丢弃该值
.
关于Scalaz Lens 到 ReaderWriterState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152019/