【问题标题】:How can I find out the classes which list types belong to?如何找出列表类型所属的类?
【发布时间】:2019-12-05 12:48:17
【问题描述】:

如何找出列表类型所属的类?

https://www.haskell.org/onlinereport/haskell2010/haskellch6.html

数据 [a] = [] | a : [a] 推导 (Eq, Ord)

列表是类 Read、Show、Eq、Ord、Monad、Functor 和 MonadPlus 的实例。

为什么以上两者不完全一致?

列表类型是Foldable 类的实例吗? 如果是,为什么上面的链接中没有提到?

谢谢。

【问题讨论】:

  • 他们做deriving意味着Haskell可以自动实现EqOrd类(这意味着你不需要自己实现这些)。其他的则使用显式的instance Monad 等实现。
  • (1) 你的意思是默认 list 不是 Monad 的实例吗?如果我想要它,我必须明确声明吗? (2) 列表类型是可折叠类的实例吗?如果是,为什么上面的链接中没有提到?
  • 不,它只是意味着 Haskell 可以自动为类型类实现某些实例:这些是 EqOrdEnumBoundedShow 和 @ 987654332@.
  • 谢谢。 (1) (2) 我不明白你的意思。 (3) 如何找出一个类型(例如列表类型)所属的所有类?
  • 使用:i,您可以找到实例列表。

标签: list haskell instance typeclass deriving


【解决方案1】:

为什么以上两者不完全一致?

这两个语句完全冲突。

deriving [Haskell'10 report] 表示编译器将自动派生实例。因此,您不需要显式定义instance 子句。该报告还指定了此自动实例的外观。

Haskell 报告提到只能自动派生有限数量的类型类:

CEqOrdEnumBoundedShowRead 之一。

某些ghc 扩展允许更多自动派生的类型类(如Functor 等)。

除了 Haskell 可以自动派生的那个之外,您还可以使用 instance block [Haskell'10 report] 手动实例化其他的。

例如,我们可以自己定义Maybe

data Maybe a = Nothing | Just a deriving (Show, Eq, Ord)

instance Functor Maybe where
    fmap _ Nothing = Nothing
    fmap f (Just x) = Just (f x)

因此,我们的Maybe 类型是ShowEqOrdFunctor 的实例。

ghci中,你可以使用:i找出一个类型属于哪个类型类,例如:

Prelude> :i []
data [] a = [] | a : [a]    -- Defined in ‘GHC.Types’
instance Eq a => Eq [a] -- Defined in ‘GHC.Classes’
instance Monad [] -- Defined in ‘GHC.Base’
instance Functor [] -- Defined in ‘GHC.Base’
instance Ord a => Ord [a] -- Defined in ‘GHC.Classes’
instance Read a => Read [a] -- Defined in ‘GHC.Read’
instance Show a => Show [a] -- Defined in ‘GHC.Show’
instance Applicative [] -- Defined in ‘GHC.Base’
instance Foldable [] -- Defined in ‘Data.Foldable’
instance Traversable [] -- Defined in ‘Data.Traversable’
instance Monoid [a] -- Defined in ‘GHC.Base’

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-12-25
    • 2015-08-27
    • 2021-09-18
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多