以下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
这为Able
,Maybe Int
等定义Maybe Bool
的实例,前提是Able
有Int
个实例,{{1}等等。
如何在Scala中做到这一点?
答案 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)