以下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中,我可以定义一种包罗万象的实例,从而为所有Maybe类型创建一个实例:
instance Able a => Able (Maybe a) where
able (Just a) = able a
able Nothing = 0
如果存在
Able
,Maybe Int
等的实例Maybe Bool
,则此方法为Able
,Int
等定义了Bool
的实例。在Scala中如何做到这一点?
最佳答案
您将根据对等类型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)