2011-12-23 108 views
2

我剛開始學習haskell,並試圖實現一個簡單的函數來檢查數字是否是平方根。我想我有一些理解Haskell類型系統的問題 - 我唯一的其他編程經驗是ruby和一些Java。這是我迄今(很抱歉,如果它真的傻):Haskell找到完美的方塊 - 獲取類型錯誤

isPerfectSquare :: (RealFloat t) => t -> Bool 
isPerfectSquare n = 
    (sqrt n) == (truncate (sqrt n)) 

這就是我會做的紅寶石......但在這裏它給了我這個錯誤:

Could not deduce (Integral t) arising from a use of `truncate' 
from the context (RealFloat t) 
    bound by the type signature for 
      isPerfectSquare :: RealFloat t => t -> Bool 
    at more.hs:(73,1)-(74,35) 
Possible fix: 
    add (Integral t) to the context of 
    the type signature for isPerfectSquare :: RealFloat t => t -> Bool 
In the second argument of `(==)', namely `(truncate (sqrt n))' 
In the expression: (sqrt n) == (truncate (sqrt n)) 
In an equation for `isPerfectSquare': 
    isPerfectSquare n = (sqrt n) == (truncate (sqrt n)) 
Failed, modules loaded: none. 

莫非你請解釋什麼是問題,如何解決問題,最好是我不瞭解的基本概念?提前致謝。

回答

5

SQRT具有類型:

sqrt :: Floating a => a -> a 

截斷具有類型:

truncate :: (RealFrac a, Integral b) => a -> b 

換句話說,SQRT返回一個浮點數,而截斷返回一個整數。你必須插入一個明確的轉換。在這種情況下,你可能想fromIntegral,它可以在任何整數類型轉換爲任何數值類型:

fromIntegral :: (Num b, Integral a) => a -> b 

然後,您可以作出比較:

(sqrt n) == (fromIntegral $ truncate (sqrt n)) 
+0

感謝,這正是我一直在尋找!我想我只需要學習很多東西。 – V9801 2011-12-23 02:19:04