给定,说
case class Person(age: Int)
val ageL: Lens[Person, Int] = ...
我该如何想出:
def incrementAge(by: Int): ReaderWriterState[Config, String, Person]
在利用ageL
镜头的同时。Scalaz Lens 有一些实用程序可以State
从.Lens
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)
.