2011-12-23 4 views
2

私はちょうどhaskellの学習を始めました。数字が平方根であるかどうかを調べる簡単な関数を実装しようとしました。私は、Haskell型システムを理解する上でいくつかの問題を抱えていると思います。私の唯一のプログラミング経験は、ルビーとJavaです。これは、(その本当に愚かな場合は申し訳ありませんが)私がこれまで持っていたものです:Haskell完全な正方形を見つける - 型エラーを取得する

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

これは私がRubyでどうなるのかです...しかし、ここで、それは私に、このエラーを与える:

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 :: (Num b, Integral a) => a -> b 

:この場合、あなたはおそらく、任意の数値型に任意の整数型に変換することができますfromIntegral、欲しい

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

おかげで、これは私が探していたまさにです!私はちょうど学ぶべきことがたくさんあると思う。 – V9801

関連する問題