當我嘗試運行此代碼時,這是一種混亂:
isSquare :: Integral n => n -> Bool
isSquare n = result
where
root = sqrt n
f = floor root
c = ceiling root
result = f == c
main = do
print (isSquare 25)
so sqrtis of typeFloating a => a -> a和flooris of type (RealFrac a, Integral b) => a -> b。顯然,我不能混合它們。我已經使用 fromRational 和 fromIntegral 和 toRational 進行了轉換,但我無法阻止編譯器抱怨:
Main.hs:4:12: error:
* Could not deduce (Floating n) arising from a use of `sqrt'
from the context: Integral n
bound by the type signature for:
isSquare :: forall n. Integral n => n -> Bool
at Main.hs:1:1-35
Possible fix:
add (Floating n) to the context of
the type signature for:
isSquare :: forall n. Integral n => n -> Bool
* In the expression: sqrt n
In an equation for `root': root = sqrt n
In an equation for `isSquare':
isSquare n
= result
where
root = sqrt n
f = floor root
c = ceiling root
result = f == c
|
4 | root = sqrt n
| ^^^^^^
Main.hs:5:9: error:
* Could not deduce (RealFrac n) arising from a use of `floor'
from the context: Integral n
bound by the type signature for:
isSquare :: forall n. Integral n => n -> Bool
at Main.hs:1:1-35
Possible fix:
add (RealFrac n) to the context of
the type signature for:
isSquare :: forall n. Integral n => n -> Bool
* In the expression: floor root
In an equation for `f': f = floor root
In an equation for `isSquare':
isSquare n
= result
where
root = sqrt n
f = floor root
c = ceiling root
result = f == c
|
5 | f = floor root
| ^^^^^^^^^^
Main.hs:6:9: error:
* Could not deduce (RealFrac n) arising from a use of `ceiling'
from the context: Integral n
bound by the type signature for:
isSquare :: forall n. Integral n => n -> Bool
at Main.hs:1:1-35
Possible fix:
add (RealFrac n) to the context of
the type signature for:
isSquare :: forall n. Integral n => n -> Bool
* In the expression: ceiling root
In an equation for `c': c = ceiling root
In an equation for `isSquare':
isSquare n
= result
where
root = sqrt n
f = floor root
c = ceiling root
result = f == c
|
6 | c = ceiling root
| ^^^^^^^^^^^^
exit status 1
如何在地板上使用 sqrt?
uj5u.com熱心網友回復:
sqrt n需要n屬于型別類成員的Floating型別,因為sqrt有 type sqrt :: Floating a => a -> a。沒有內置的數字型別既是型別類的成員,Integral又是型別類的成員Floating:這沒有多大意義,因為兩者處理不同型別的數字。
您可以使用任何型別fromIntegral :: (Integral a, Num b) => a -> b的數字轉換Integral為任何Num型別。因此,我們可以將其用于:
isSquare :: Integral n => n -> Bool
isSquare n = floor root == ceiling root
where root = sqrt (fromIntegral n)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/423006.html
標籤:
上一篇:檔案開頭無用的種類相等錯誤
下一篇:實體電感作為約束
