加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala vs Haskell类型类:“catchall”实例

发布时间:2020-12-16 09:01:08 所属栏目:安全 来源:网络整理
导读:以下 Haskell类型类和实例: class Able a where able :: a - Intinstance 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中,
以下 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 for Maybe Int,Maybe Bool等的实例,前提是有一个实例Able for 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读