1

我在 Haskell 中编程,但在使用以下代码时遇到问题:

exactRootList :: Int -> Int -> [Int]
exactRootList ini end = 
      [x | x<-[ini .. end],  (floor (sqrt x)) == (ceiling (sqrt x))]

然后,当我执行时:

> hugs myprogram.hs

我明白了

Error Instances of (Floating Int, RealFrac Int) required for definition of exactRootList

我不明白这个错误。

我的程序应该在区间 [a, b] 上显示一个精确根为 4 或 9 的数字列表,其中 a 和 b 是函数的两个参数。例子:

exactRootList 1 10

它必须返回

1 4 9

因为在 1 和 10 之间,只有 1、4 和 9 具有精确根。

问候!

4

1 回答 1

6

如果您查看sqrt您看到的类型,它仅适用于以下实例的类型Floating

> :t sqrt
sqrt :: Floating a => a -> a

您可能知道,Int它不是浮点值。您需要使用以下方法转换您的整数(变量xfromIntegral

[x | x<-[ini .. end],  let a = fromIntegral x
                       in (floor (sqrt a)) == (ceiling (sqrt a))]
于 2011-10-14T04:02:29.837 回答