gpt4 book ai didi

列表类型错误的 Haskell 列表

转载 作者:行者123 更新时间:2023-12-04 17:47:02 25 4
gpt4 key购买 nike

在 GHCi 中,我输入

let xs = [1, 'a']

它立即提示错误:
<interactive>:28:11:
No instance for (Num Char) arising from the literal ‘1’
In the expression: 1
In the expression: [1, 'a']
In an equation for ‘xs’: xs = [1, 'a']

但是,当我输入
let xs = [1, [1, 1]]

刚刚过去。当我尝试打印 xs 时它会提示:
<interactive>:5:1:
No instance for (Num [t0]) arising from a use of ‘it’
In a stmt of an interactive GHCi command: print it

我认为 Haskell 是一种静态类型语言,因此应该在编译时捕获任何类型错误。我想知道为什么在不同的时间捕获上述 2 个错误?

最佳答案

1Num a => a 类型的多态值.所以在 [1, [2, 3]] , 我们有 [2, 3] :: Num a => [a] ;由于所有列表元素必须具有相同的类型,我们得出结论,我们必须有 1 :: Num a => [a] .这有点奇怪——想起来很奇怪 1作为具有列表类型 - 但如果有人创建了一个足够奇怪的 Num 实例,则它是完全有效的。 .检查实例是否存在会被推迟,直到您尝试使用该实例;这使您有机会在使用实例定义值后定义实例。因此,在您尝试对列表 [1, [2, 3]] 实际执行某些操作之前,它不会提示。 .

为了说明我的意思,人们可以这样写:

instance Num a => Num [a] where
fromInteger n = pure (fromInteger n)
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
abs = liftA abs
signum = liftA signum

(实际上,这个实例适用于任何 Applicative ,有时甚至很有用。)然后,在 ghci 中:
> let xs = [1, [1, 1]]
> xs
[[1],[1,1]]

看 ma,没有错误!

关于列表类型错误的 Haskell 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30655941/

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