scalaz List [StateT] .sequence - 找不到参数n的隐式值:scalaz.Applicative

时间:2011-10-16 05:39:46

标签: scala scalaz monad-transformers state-monad

我正在尝试根据对Scalaz state monad examples答案的评论,弄清楚如何使用StateT组合两个State状态变换器。

我似乎非常接近,但在尝试申请sequence时遇到了问题。

import scalaz._
import Scalaz._
import java.util.Random

val die = state[Random, Int](r => (r, r.nextInt(6) + 1))

val twoDice = for (d1 <- die; d2 <- die) yield (d1, d2)

def freqSum(dice: (Int, Int)) = state[Map[Int,Int], Int]{ freq =>
  val s = dice._1 + dice._2
  val tuple = s -> (freq.getOrElse(s, 0) + 1)
  (freq + tuple, s)
}

type StateMap[x] = State[Map[Int,Int], x]

val diceAndFreqSum = stateT[StateMap, Random, Int]{ random =>
  val (newRandom, dice) = twoDice apply random
  for (sum <- freqSum(dice)) yield (newRandom, sum)
}

所以我得到了一个StateT[StateMap, Random, Int],我可以解开初始的随机和空地图状态:

val (freq, sum) = diceAndFreqSum ! new Random(1L) apply Map[Int,Int]()
// freq: Map[Int,Int] = Map(9 -> 1)
// sum: Int = 9

现在,我想要生成StateT的列表并使用sequence,以便我可以致电list.sequence ! new Random(1L) apply Map[Int,Int]()。但是当我尝试这个时,我得到了:

type StT[x] = StateT[StateMap, Random, x]
val data: List[StT[Int]] = List.fill(10)(diceAndFreqSum)
data.sequence[StT, Int]

//error: could not find implicit value for parameter n: scalaz.Applicative[StT]
          data.sequence[StT, Int]
                       ^

有什么想法吗?我可以在最后一段时间使用一些帮助 - 假设它是可能的。

1 个答案:

答案 0 :(得分:9)

看着scalaz Monad source,我注意到有implicit def StateTMonad确认StateT[M, A, x]是类型参数x的monad。 monad也是应用程序,通过查看the definition of the Monad特征并在REPL中查看来确认:

scala> implicitly[Monad[StT] <:< Applicative[StT]]
res1: <:<[scalaz.Monad[StT],scalaz.Applicative[StT]] = <function1>

scala> implicitly[Monad[StT]]
res2: scalaz.Monad[StT] = scalaz.MonadLow$$anon$1@1cce278

所以这给了我一个定义隐式Applicative[StT]以帮助编译器的想法:

type StT[x] = StateT[StateMap, Random, x]
implicit val applicativeStT: Applicative[StT] = implicitly[Monad[StT]]

这就是诀窍:

val data: List[StT[Int]] = List.fill(10)(diceAndFreqSum)
val (frequencies, sums) =
  data.sequence[StT, Int] ! new Random(1L) apply Map[Int,Int]()

// frequencies: Map[Int,Int] = Map(10 -> 1, 6 -> 3, 9 -> 1, 7 -> 1, 8 -> 2, 4 -> 2)
// sums: List[Int] = List(9, 6, 8, 8, 10, 4, 6, 6, 4, 7)