2016-02-15 42 views
7

下Haskell的类型类和实例:斯卡拉VS哈斯克尔类型类:“包罗万象”的情况下

class Able a where 
    able :: a -> Int 

instance Able Int where 
    able x = x 

通常翻译为斯卡拉,像这样:

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

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

在Haskell我现在可以定义排序从而为所有可能的类型创建一个实例:

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

这定义了一个instanc为Maybe IntMaybe BoolAble E中提供有对IntBool实例Able

一个会怎么做,在Scala呢?

回答

11

您将从隐式参数为对等类型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) 
+0

巧妙!非常感谢你 :) – scravy