我正在使用 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, ?]] {
// ...
}
}
?
由于类型未知,因此无法编译。