gpt4 book ai didi

haskell 初学者

转载 作者:行者123 更新时间:2023-12-04 01:26:19 27 4
gpt4 key购买 nike

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

最佳答案

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是一个类型构造函数,因为它用于构造新类型(结果类型取决于 a 中的 Maybe a 的类型),其中这种类型可能是 Maybe Int (注意,不再有类型参数 a,即所有类型参数都已绑定(bind))。 Just aNothing是数据构造器,因为它们用于构造某个 Maybe 的实例输入,例如 Just Int创建 Maybe Int 的实例.

另一个主要区别是您只能在模式匹配时使用数据构造函数。你不能说:
case foo of
Maybe a -> ...

你不得不说:
case foo of
Just a -> ...
Nothing -> ...

关于 haskell 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947486/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com