Scala vs Haskell类型类:“catchall”实例

时间:2016-02-15 21:59:53

标签: scala haskell typeclass implicit scala-implicits

以下Haskell类型类和实例:

class Able a where
  able :: a -> Int

instance Able Int where
  able x = x

通常被翻译成Scala,如下所示:

trait Able[A] {
  def able(a: A): Int
}

implicit object AbleInt extends Able[Int] {
  def able(a: Int) = a
}

在Haskell中,我现在可以定义一种catch-all实例,从而为所有Maybe类型创建一个实例:

instance Able a => Able (Maybe a) where
  able (Just a) = able a
  able Nothing  = 0

这为AbleMaybe Int等定义Maybe Bool的实例,前提是AbleInt个实例,{{1}等等。

如何在Scala中做到这一点?

1 个答案:

答案 0 :(得分:12)

您将从对等类型A的实例的隐式参数构造实例。例如:

implicit def AbleOption[A](implicit peer: Able[A]) = new Able[Option[A]] {
  def able(a: Option[A]) = a match {
    case Some(x) => peer.able(x)
    case None    => 0
  }
}

assert(implicitly[Able[Option[Int]]].able(None)    == 0)
assert(implicitly[Able[Option[Int]]].able(Some(3)) == 3)