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

标签 scala scalaz monad-transformers state-monad

我想弄清楚如何使用 StateT结合两个 State基于对我的 Scalaz state monad examples 的评论的状态转换器回答。

看来我已经很接近了,但是在尝试申请 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]我可以用初始随机和空 map 状态展开:
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]
                       ^

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

最佳答案

啊看着scalaz Monad source ,我注意到有一个 implicit def StateTMonad这证实了 StateT[M, A, x]是类型参数 x 的 monad。单子(monad)也是应用程序,通过查看 the definition of the Monad 得到了证实。 trait 并通过戳 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)

关于scalaz List[StateT].sequence - 找不到参数 n 的隐式值 : scalaz. 适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782589/

相关文章:

haskell - 暂停单子(monad)

Scala 组合;共产法?

java - 如何在 Scala 中获取 void.class?

scala - 光滑 3 : How to construct dynamic filter with optional column?

scala - | @ |的验证用法在 Scalaz

haskell - 在haskell程序中使用返回的EitherT

scala - for之后如何避免平面图

基于 Scala 类型的属性提取器 - Getter only Lens?

scala - 当你有 andThen 时映射函数很有用

haskell - 提取嵌套 Exception monad 转换器的左值