gpt4 book ai didi

haskell - 关于 Haskell 类型类(Num vs Read)

转载 作者:行者123 更新时间:2023-12-04 05:30:06 24 4
gpt4 key购买 nike

有人可以解释一下我在这里缺少什么:

Prelude> :t read
read :: (Read a) => String -> a
Prelude> read "4"

<interactive>:1:0:
Ambiguous type variable `a' in the constraint:
`Read a' arising from a use of `read' at <interactive>:1:0-7
Probable fix: add a type signature that fixes these type variable(s)
read "4"引发错误,因为 ghci 不知道我们想要哪种具体类型,它只知道我们有一个 Read类型类。 read "4" :: Int工作正常。这对我来说很清楚。

现在,按照上述逻辑,我期望 fromIntegral 4引发错误:
Prelude> :t fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b
Prelude> fromIntegral 4
4

但是,它工作正常。为什么在这种情况下不需要类型注释?我预计上述方法会失败;并且只有
Prelude> fromIntegral 4 :: Int

去工作。

注意 - 我正在阅读“为你学习 Haskell 非常有用”,并且已经涵盖到第 5 章。我的要求是否在第 7 章(或其他章节)中讨论过?

谢谢。

最佳答案

它之所以有效是因为 type defaulting ,这会导致不明确的类型变量默认为 IntegerDouble (或其他一些用户定义的默认值)。这只发生在 Num及其子类。

在 GHCi 中,the rules for defaulting are relaxed也为 Show 工作, EqOrd ,还有 ()被添加到默认类型列表中。这允许像 [] == [] 这样的表达式类型检查。

关于haskell - 关于 Haskell 类型类(Num vs Read),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228444/

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