Int instance Able Int where able x = x 通常像这样翻-6ren">
gpt4 book ai didi

Scala vs Haskell 类型类 : "catchall" instances

转载 作者:行者123 更新时间:2023-12-04 14:08:16 24 4
gpt4 key购买 nike

以下 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 , ETC。

在 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)

关于Scala vs Haskell 类型类 : "catchall" instances,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com