【问题标题】:Scala vs Haskell typeclasses: "catchall" instancesScala vs Haskell 类型类:“catchall”实例
【发布时间】:2016-02-15 21:59:53
【问题描述】:

以下 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

这为Maybe IntMaybe Bool 等定义了一个Able 的实例,前提是IntBool 等有一个实例Able

在 Scala 中如何做到这一点?

【问题讨论】:

    标签: scala haskell typeclass implicit scala-implicits


    【解决方案1】:

    您可以从对等类型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)
    

    【讨论】:

    • 巧妙!非常感谢:)
    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2017-04-17
    • 2015-09-07
    • 2017-01-14
    相关资源
    最近更新 更多