2016-02-15 40 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