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)
)
这不允许您以相同的方式组合地使用这些操作,但在某些情况下它可能就是您所需要的。