我不明白为什么我会从 GHCi 得到以下回复。不是Maybe
构造函数吗?
Prelude> :t Maybe
<interactive>:1:1: Not in scope: data constructor `Maybe'
Prelude> let e = Maybe 5
<interactive>:1:9: Not in scope: data constructor `Maybe'
Maybe
是一个类型构造函数,它的两个可能的数据构造函数是Nothing
和Just
。所以你必须说Just 5
而不是Maybe 5
。
> let x = Just 5
> x
Just 5
> let y = Nothing
> y
Nothing
> :type x
x :: Maybe Integer
> :type y
y :: Maybe a
> :info Maybe
data Maybe a = Nothing | Just a -- Defined in Data.Maybe
instance Eq a => Eq (Maybe a) -- Defined in Data.Maybe
instance Monad Maybe -- Defined in Data.Maybe
instance Functor Maybe -- Defined in Data.Maybe
instance Ord a => Ord (Maybe a) -- Defined in Data.Maybe
instance Read a => Read (Maybe a) -- Defined in GHC.Read
instance Show a => Show (Maybe a) -- Defined in GHC.Show
Maybe
是一个类型构造函数,因为它用于构造新类型(结果类型取决于a
in的类型Maybe a
),其中可能是这样的类型Maybe Int
(注意,a
不再有类型参数,即所有类型参数都已绑定)。Just a
并且Nothing
是数据构造函数,因为它们用于构造某种Maybe
类型的实例,例如Just Int
创建Maybe Int
.
另一个主要区别是您只能在模式匹配时使用数据构造函数。你不能说:
case foo of
Maybe a -> ...
你不得不说:
case foo of
Just a -> ...
Nothing -> ...
Maybe
是类型名称。该类型的构造函数是Just
and Nothing
,因此 Maybe 类型的实际值可以是以下形式Just 5
(对于您要返回的值的情况)或Nothing
(对于空的情况)。