【发布时间】:2021-12-22 10:35:46
【问题描述】:
我正在尝试创建一个毕达哥拉斯三元组列表,即每个包含(x, y, z) 的元组列表,使得x^2 + y^2 = z^2 和x、y、z 在[1..n] 范围内.
我在列表理解保护中遇到了似乎是类型错误的问题。这是我的代码:
-- integer square root
isqrt :: Int -> Float
isqrt = sqrt . fromIntegral
-- hypotenuse
hyp :: Int -> Int -> Float
hyp x y = isqrt (x^2 + y^2)
-- pythagorean triplets in range [1..n]
pyths :: Int -> [(Int, Int, Int)]
pyths n = [(x, y, truncate (hyp x y)) | x <- [1..n], y <- [x..n], elem (hyp x y) [1..n]]
这是错误:
• Couldn't match expected type ‘Float’ with actual type ‘Int’
• In the expression: n
In the second argument of ‘elem’, namely ‘[1 .. n]’
In the expression: elem (hyp x y) [1 .. n]
|
11 | pyths n = [(x, y, truncate (hyp x y)) | x <- [1..n], y <- [x..n], elem (hyp x y) [1..n]]
|
我可以通过将我的守卫从elem (hyp x y) [1..n] 编辑为elem (hyp x y) [1..fromIntegral n] 来解决该错误,这表明变量n 在列表中的某个时刻以某种方式从Int 转换为Float理解。
与[1..5] 相比,[1..fromIntegral n] 看起来并不特别简洁或优雅,我应该使用另一种方法来解决或避免这个问题吗?
【问题讨论】:
标签: haskell list-comprehension typeerror