我把头包裹在州立大学附近。琐碎的例子很容易理解。我现在转向一个现实世界的案例,其中域对象是复合的。例如,使用以下域对象(它们没有多大意义,只是纯粹的例子):
case class Master(workers: Map[String, Worker])
case class Worker(elapsed: Long, result: Vector[String])
case class Message(workerId: String, work: String, elapsed: Long)
在Worker
monad中考虑S
作为State[S, +A]
类型,可以很容易地编写一些这样的组合器:
type WorkerState[+A] = State[Worker, A]
def update(message: Message): WorkerState[Unit] = State.modify { w =>
w.copy(elapsed = w.elapsed + message.elapsed,
result = w.result :+ message.work)
}
def getWork: WorkerState[Vector[String]] = State { w => (w.result, w) }
def getElapsed: WorkerState[Long] = State { w => (w.elapsed, w) }
def updateAndGetElapsed(message: Message): WorkerState[Long] = for {
_ <- update(message)
elapsed <- getElapsed
} yield elapsed
// etc.
将这些与Master
状态组合器相结合的惯用方法是什么? e.g。
type MasterState[+A] = State[Master, A]
def updateAndGetElapsedTime(message: Message): MasterState[Option[Long]]
我可以这样实现:
def updateAndGetElapsedTime(message: Message): MasterState[Option[Long]] =
State { m =>
m.workers.get(message.workerId) match {
case None => (None, m)
case Some(w) =>
val (t, newW) = updateAndGetElapsed(message).run(w)
(Some(t), m.copy(m.workers.updated(message.workerId, newW))
}
}
我不喜欢的是我必须在最后一个变压器内手动运行State monad。我的现实世界的例子有点涉及。使用这种方法很快就会变得混乱。
是否有更惯用的方式来运行这种增量更新?
答案 0 :(得分:8)
通过组合镜头和状态monad可以很好地完成这项工作。首先进行设置(我已经编辑了你的,以便用Scalaz 7.1进行编译):
case class Master(workers: Map[String, Worker])
case class Worker(elapsed: Long, result: Vector[String])
case class Message(workerId: String, work: String, elapsed: Long)
import scalaz._, Scalaz._
type WorkerState[A] = State[Worker, A]
def update(message: Message): WorkerState[Unit] = State.modify { w =>
w.copy(
elapsed = w.elapsed + message.elapsed,
result = w.result :+ message.work
)
}
def getWork: WorkerState[Vector[String]] = State.gets(_.result)
def getElapsed: WorkerState[Long] = State.gets(_.elapsed)
def updateAndGetElapsed(message: Message): WorkerState[Long] = for {
_ <- update(message)
elapsed <- getElapsed
} yield elapsed
现在有几个通用镜头可以让我们查看Master
:
val workersLens: Lens[Master, Map[String, Worker]] = Lens.lensu(
(m, ws) => m.copy(workers = ws),
_.workers
)
def workerLens(workerId: String): PLens[Master, Worker] =
workersLens.partial andThen PLens.mapVPLens(workerId)
然后我们基本完成了:
def updateAndGetElapsedTime(message: Message): State[Master, Option[Long]] =
workerLens(message.workerId) %%= updateAndGetElapsed(message)
这里%%=
告诉我们,一旦我们通过镜头放大到合适的工作人员,将执行什么状态操作。