gpt4 book ai didi

list - Haskell 列表理解(为列表元素打印 sqrt)

转载 作者:行者123 更新时间:2023-12-05 01:00:46 24 4
gpt4 key购买 nike

我有 GHCi,版本 7.8.3。我想计算可被 10 整除的 sqrt 项的总和。

如果我写 [ x | x <- [10..100], x `mod` 10 == 0]sum [sqrt x | x <- [10..100]]是正确的。

但是如果我写 sum [ sqrt x | x <- [10..100], x `mod` 10 == 0]当显示错误时:

'<interactive>:39:1:
No instance for (Show t0) arising from a use of ‘print’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
instance Show Double -- Defined in ‘GHC.Float’
instance Show Float -- Defined in ‘GHC.Float’
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
...plus 23 others
In a stmt of an interactive GHCi command: print it'

怎么改命令,那个程序是正确的?

最佳答案

问题来自这样一个事实,即当您使用 mod 时,数字的类型必须是 Integral a => a ,以及当您使用 sqrt 时数字类型必须是Floating a => a . GHC 知道没有任何类型适合这两个约束,尽管因为您在 GHCi 中执行它,无论出于何种原因的错误消息几乎都是无用的。错误信息是这样的,因为 GHCi 使用 print , 调用 show ,出于某种原因,这是第一个被检查的约束。由于没有类型具有约束 Show , Integral , 和 Floating ,它不进行类型检查。

您的另外两个示例类型检查,因为它们仅使用 mod 之一或 sqrt .您可以使用 fromIntegral 获得两者的组合。申请前sqrt :

sum [sqrt $ fromIntegral x | x <- [10..100], x `mod` 10 == 0]

关于list - Haskell 列表理解(为列表元素打印 sqrt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29099693/

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