haskell - Haskell 中 Nothing 的类型是什么?

标签 haskell types

我在页面118 《为大善而学 Haskell!》一书的内容

那里写着:

ghci> :t Nothing 
Nothing :: Maybe a

这是我的问题:

如果我理解正确的话,Nothing 是一个值,只有具体类型可以有值,但 Maybe a 不是具体类型。那么它怎么会有值 Nothing 呢?

书上还说:

Notice that the type of Nothing is Maybe a. Its type is polymorphic.

多态类型是什么意思?我该如何理解这一点?这是否与只有具体类型才能具有值的规则相矛盾?

编辑:

摘自本书的 PDF 版本:

We say that a type is concrete if it doesn't take any type parameters at all (like Int or Bool), or if it takes type parameters and they're all filled up (like Maybe Char). If you have some value, its type is always a concrete type.

最佳答案

这并不矛盾。 Nothing 是一个值,其具体类型可以是 Maybe a 的任何可能实例。

否则,Maybe a 类型的值将继续具有具体类型 Maybe IntMaybe StringMaybe Another code>,特别是 Nothing 可以由它们每个人键入,具体取决于上下文。这是因为它的构造函数(再次称为 Nothing::Maybe a)不接受任何参数,因此可以按原样调用它来生成 Maybe a 类型的值。如果您愿意,我们将为每种具体类型提供一个。

如果没有上下文,ghci 当然会为您提供它可以推断出 Nothing 的最通用类型,即 Maybe a,但这不是它的具体类型。这取决于您将在其中使用 Nothing 的各个表达式。例如:

ghci> Nothing
Nothing
it :: Maybe a

这可能是您输入的内容,或者类似的内容。没有进一步的上下文,因此 Nothing 不会使用具体类型进行键入。

ghci> Nothing :: Maybe Int
Nothing
it :: Maybe Int

这里我强制它采用具体类型Maybe Int

ghci> 1 + fromMaybe 2 Nothing
3
it :: Integer

如果我将它与整数之和混合 (fromMaybe::a -> Maybe a -> a 接受默认值和 Maybe a 并返回Just 中的值或默认的 Nothing),则系统会将 Nothing 键入为 Maybe Integer ,因为您希望从中提取一个整数。没有,所以在本例中我们将 1 与默认的 2 相加。

ghci> 1 + fromMaybe 2 (Nothing :: Maybe Integer)
3
it :: Integer

同样,请仔细检查。我们强制 Nothing 具有我们之前在同一表达式中假设的具体类型。

ghci> 1 + fromMaybe 2 (Nothing :: Maybe Char)

<interactive>:1:15:
    No instance for (Num Char)
      arising from the literal `2'
    Possible fix: add an instance declaration for (Num Char)
    In the first argument of `fromMaybe', namely `2'
    In the second argument of `(+)', namely
      `fromMaybe 2 (Nothing :: Maybe Char)'
    In the expression: 1 + fromMaybe 2 (Nothing :: Maybe Char)

为了进行三重检查,如果我们强制它采用另一种具体类型,如您所见,它的值将完全不同,从而导致类型错误(与 C 不同,在 Haskell 中 Char 不会充当数字)。

关于haskell - Haskell 中 Nothing 的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22065358/

相关文章:

haskell - 为什么安全偏函数使用 Maybe 而不是泛化到任何 Monad

haskell - 直到最后一次出现 Haskell 中的模式

haskell - 取决于上下文的多态返回类型

postgresql - 如何使用动态 SQL 设置复合变量字段的值

haskell - 将 `do notation` 转换为 >>= v.map

haskell - 使用 Haskell 进行网页抓取

php - 是真的吗(在 PHP 中)?

c++ - 遍历模块中的所有结构

types - 在 Julia 中找出变量的类型

Haskell:通过 "Principled Transformations"简化函数