【发布时间】:2016-04-16 15:14:58
【问题描述】:
我正在使用 Scalaz,因为我喜欢标准库中 Haskell 类型类设置的很多方面。但这正是我目前的问题。我有一个带有两个通用参数的通用数据结构:
case class Parser[T,A](f: T => (T,A))
在 Haskell 中,我会像这样实现 Alternative 类型类:
newtype Parser t a = Parser { runParser :: t -> (t,a) }
instance Alternative (Parser t) where
...
但是我怎样才能在 Scala 中做一些等效的事情呢?据我所知,我不能做类似的事情
object Parser {
implicit def ins_Alternative[T] = new Alternative[Parser[T]] {
// ...
}
}
有人知道怎么做吗?提前谢谢!
更新:
我发现了这个:
implicit def eitherMonad[L]: Traverse[Either[L, ?]] with MonadError[Either[L, ?], L] with BindRec[Either[L, ?]] with Cozip[Either[L, ?]] =
new Traverse[Either[L, ?]] with MonadError[Either[L, ?], L] with BindRec[Either[L, ?]] with Cozip[Either[L, ?]] {
def bind[A, B](fa: Either[L, A])(f: A => Either[L, B]) = fa match {
case Left(a) => Left(a)
case Right(b) => f(b)
}
// ...
}
在 Scalaz 源 (https://github.com/scalaz/scalaz/blob/series/7.3.x/core/src/main/scala/scalaz/std/Either.scala) 中。
据此我想我必须写一些类似的东西
object Parser {
implicit def ins_Alternative[T] = new Alternative[Parser[T, ?]] {
// ...
}
}
由于类型 ? 未知而无法编译。
【问题讨论】:
-
要使用
Parser[T, ?]语法,您需要kind-projector 编译器插件。 -
@AlexeyRomanov 很高兴知道。非常感谢!