【问题标题】:Scalaz sequenceU and IndexStateT compilation issueScalaz sequenceU 和 IndexStateT 编译问题
【发布时间】:2015-07-21 11:18:04
【问题描述】:

以下示例代码中有两个函数:runFrun

import scalaz._, Scalaz._
import scala.concurrent.Future

sealed class Controller[TState]
{
  def genStartState (): TState = ???
  implicit val m = Monoid.instance[Boolean] (_ | _, false)

  def runF ()(implicit f: Monad[Future]) : Future[Boolean] =
  {
    val tasks : List[StateT[Future, TState, Boolean]]
      = ???

    val indexed : IndexedStateT[Future, TState, TState, List[Boolean]]
      = tasks.sequenceU

    val mapped : IndexedStateT[Future, TState, TState, Boolean]
      = indexed.map { results => results.foldMap (identity) }

    val result : Future[Boolean]
      = mapped.eval (genStartState ())

    result
  }

  def run[T[+_]: Monad] () : T[Boolean] =
  {
    val tasks: List[StateT[T, TState, Boolean]]
      = ???

    val indexed: IndexedStateT[T, TState, TState, List[Boolean]]
      = tasks.sequenceU

    val mapped: IndexedStateT[T, TState, TState, Boolean]
      = indexed.map { results => results.foldMap (identity) }

    val result: T[Boolean]
      = mapped.eval (genStartState ())

    result
  }
}

runF 编译,run 不编译。

我不知道如何让run编译,我得到以下两个错误:

[error] could not find implicit value for parameter F: scalaz.MonadState[StateTT,CS]
[error]     val monadStateT = MonadState[StateTT, CS]
[error]                                 ^
[error] Implicit not found: scalaz.Unapply[scalaz.Applicative, scalaz.StateT[T,TState,Boolean]]. Unable to unapply type `scalaz.StateT[T,TState,Boolean]` into a type constructor of kind `M[_]` that is classified by the type class `scalaz.Applicative`. Check that the type class is defined by compiling `implicitly[scalaz.Applicative[type constructor]]` and review the implicits in object Unapply, which only cover common type 'shapes.'
[error]     = stateTransformers.sequenceU
[error]                         ^

这两个函数的唯一区别是我试图使runF 通用,所以我可以使用不同的HKT。

【问题讨论】:

  • T 必须是协变的吗?删除+ 会更干净地修复所有问题。

标签: scalaz


【解决方案1】:

不确定这是否是最好的方法,但我设法通过定义以下隐式 Applicative 使其工作:

type ST[α] = StateT[T, TState, α]

implicit val a: Applicative[ST] = new Applicative[ST] {

  def point[A](a: => A): ST[A] =
    StateT ((s: TState) => Applicative[T].point ((s, a)))

  def ap[A, B](fa: => ST[A])(f: => ST[A => B]): ST[B] =
    for { az <- fa; fz <- f } yield fz (az)
}

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多