【问题标题】:Scala multiple generic parameter data structure typeclass instanceScala多泛型参数数据结构类型类实例
【发布时间】: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 很高兴知道。非常感谢!

标签: scala scalaz7


【解决方案1】:

我找到了解决办法。

implicit def ins_Alternative[T] = new Alternative[({type x[a] = Parser[T, a]})#x] {
  override def empty[A]: Parser[T, A] = ???

  override def plus[A](a: Parser[T, A], b: => Parser[T, A]): Parser[T, A] = ???

  override def point[A](a: => A): Parser[T, A] = ???

  override def ap[A, B](fa: => Parser[T, A])(f: => Parser[T, (A) => B]): Parser[T, B] = ???
}

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多