Haskell初学者

时间:2011-10-30 20:06:27

标签: haskell maybe

我不明白为什么我从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'

2 个答案:

答案 0 :(得分:25)

Maybetype constructor,其中两个可能data constructorsNothingJust。所以你必须说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是一个类型构造函数,因为它用于构造新类型(结果类型取决于aMaybe a的类型),其中这样的类型可能是{{ 1}}(注意,不再有类型参数Maybe Int,即所有类型参数都被绑定)。 aJust a是数据构造函数,因为它们用于构造某个Nothing类型的实例,例如Maybe创建Just Int的实例。

另一个主要区别是您只能在模式匹配时使用数据构造函数。你不能说:

Maybe Int

你必须说:

case foo of
     Maybe a -> ...

答案 1 :(得分:6)

Maybe类型名称。该类型的构造函数是JustNothing,因此Maybe类型的实际Just 5形式(对于有{a}}的情况你想要返回的值)或Nothing(对于空案例)。