2

给定,说

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

我该如何想出:

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

在利用ageL镜头的同时。Scalaz Lens 有一些实用程序可以State从.LensReaderWriterState

4

1 回答 1

2

您可以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).

于 2015-05-10T15:54:13.583 回答