我不明白为什么我从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'
答案 0 :(得分:25)
Maybe
是type constructor,其中两个可能data constructors是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
中Maybe a
的类型),其中这样的类型可能是{{ 1}}(注意,不再有类型参数Maybe Int
,即所有类型参数都被绑定)。 a
和Just a
是数据构造函数,因为它们用于构造某个Nothing
类型的实例,例如Maybe
创建Just Int
的实例。
另一个主要区别是您只能在模式匹配时使用数据构造函数。你不能说:
Maybe Int
你必须说:
case foo of
Maybe a -> ...
答案 1 :(得分:6)
Maybe
是类型名称。该类型的构造函数是Just
和Nothing
,因此Maybe类型的实际值是Just 5
形式(对于有{a}}的情况你想要返回的值)或Nothing
(对于空案例)。