7

Scalaz State monad 的modify签名如下:

def modify[S](f: S => S): State[S, Unit]

Record这允许将状态替换为相同类型的状态,但当状态包含无形状值(例如,其类型会随着新字段的添加而更改)时,这将无法正常工作。在这种情况下,我们需要的是:

def modify[S, T](f: S => T): State[T, Unit]

什么是调整 Scalaz 的 State monad 以使用无形状态的好方法,以便人们可以使用 Records 而不是可怕的Map[String, Any]?

例子:

case class S[L <: HList](total: Int, scratch: L)

def contrivedAdd[L <: HList](n: Int): State[S[L], Int] =
  for {
    a <- init
    _ <- modify(s => S(s.total + n, ('latestAddend ->> n) :: s.scratch))
    r <- get
  } yield r.total

更新:

特拉维斯答案的完整代码在这里

4

1 回答 1

8

State是更通用类型的类型别名,IndexedStateT专门设计用于表示将状态类型更改为状态计算的函数:

type StateT[F[_], S, A] = IndexedStateT[F, S, S, A]
type State[S, A] = StateT[Id, S, A]

虽然无法编写您的modify[S, T]using State,但可以使用IndexedState(这是另一种类型别名,用于IndexedStateT将效果类型固定为Id):

import scalaz._, Scalaz._

def transform[S, T](f: S => T): IndexedState[S, T, Unit] =
  IndexedState(s => (f(s), ()))

你甚至可以在for-comprehensions 中使用它(这对我来说总是有点奇怪,因为单子类型在操作之间会发生变化,但它可以工作):

val s = for {
  a <- init[Int];
  _ <- transform[Int, Double](_.toDouble)
  _ <- transform[Double, String](_.toString)
  r <- get
} yield r * a

接着:

scala> s(5)
res5: scalaz.Id.Id[(String, String)] = (5.0,5.05.05.05.05.0)

在您的情况下,您可能会编写如下内容:

import shapeless._, shapeless.labelled.{ FieldType, field }

case class S[L <: HList](total: Int, scratch: L)

def addField[K <: Symbol, A, L <: HList](k: Witness.Aux[K], a: A)(
  f: Int => Int
): IndexedState[S[L], S[FieldType[K, A] :: L], Unit] =
  IndexedState(s => (S(f(s.total), field[K](a) :: s.scratch), ()))

接着:

def contrivedAdd[L <: HList](n: Int) = for {
  a <- init[S[L]]
  _ <- addField('latestAdded, n)(_ + n)
  r <- get
} yield r.total

(这可能不是分解更新操作的最佳方法,但它显示了基本思想是如何工作的。)

还值得注意的是,如果您不关心将状态转换表示为状态计算,则可以imap在任何 old 上使用State

init[S[HNil]].imap(s =>
  S(1, field[Witness.`'latestAdded`.T](1) :: s.scratch)
)

这不允许您以相同的方式组合地使用这些操作,但在某些情况下它可能就是您所需要的。

于 2016-01-19T15:43:16.637 回答