如何找出列表类型所属的类?
在 https://www.haskell.org/onlinereport/haskell2010/haskellch6.html说
data [a] = [] | a : [a] deriving (Eq, Ord)
和
Lists are an instance of classes Read, Show, Eq, Ord, Monad, Functor, and MonadPlus.
为什么上面两者不完全一致?
列表类型是 Foldable
类的实例吗?
如果是,为什么上面的链接中没有提到?
谢谢。
最佳答案
Why do the two above not agree completely with each other?
这两个陈述根本不冲突。
一个deriving
[Haskell'10 report]意味着编译器将自动派生实例。因此,您不需要显式定义 instance
子句。该报告还指定了此自动实例的外观。
Haskell 报告提到,只能自动派生有限数量的类型类:
C is one of
Eq
,Ord
,Enum
,Bounded
,Show
, orRead
.
某些ghc
扩展允许更多自动派生类型类(例如Functor
等)。
除了 Haskell 可以自动派生的之外,您还可以使用 instance
block [Haskell'10 report] 手动实例化其他实例。 .
例如,我们可以自己定义也许
:
data Maybe a = Nothing | Just a <b>deriving</b> (Show, Eq, Ord)
<b>instance</b> Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)
我们的Maybe
类型因此是Show
、Eq
、Ord
和Functor<的实例
这里。
在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’
关于list - 如何找出列表类型所属的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57232488/