我正在嘗試創建一個勾股三元組串列,即每個包含 (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]to編輯我的守衛來解決錯誤elem (hyp x y) [1..fromIntegral n],這向我表明變數n在串列理解程序中的某個時刻以某種方式從 Int 轉換為 Float。
該[1..fromIntegral n]不會顯得格外簡潔或優雅相比[1..5],有另一種方法,我應該使用要么解決或避免這個問題?
uj5u.com熱心網友回復:
這向我表明變數 n 在串列理解程序中的某個時刻以某種方式從 Int 轉換為 Float。
恰恰相反。您已經在型別簽名中宣告n為 an Int,并且永遠修復了它。在Float這里hyp x y。你在問是否hyp x y是 的element [1..n]。elem :: a -> [a] -> Bool,所以只有當你有一個與串列元素型別相同的物件時,問這個問題才有意義。這就是不匹配:要elem與 aFloat和串列一起使用,您需要該串列是 a [Float]。但由于串列是[1..n],它顯然是一個[Int].
至于你應該做些什么不同的事情,我建議不要對這個函式使用任何浮點演算法。對于您正在使用的音階來說,這可能沒問題,但我太擔心舍入錯誤會給我錯誤的答案。sqrt (a^2 b^2)您可以搜索這樣的三元組,而不是搜索需要 sqrt 的整數對a^2 b^2 == c^2。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/355728.html
下一篇:從數字串列中回傳加權平均值的函式
