Int和小数值之间的转换

Vic*_*lar 1 haskell floating

我在Haskell编程,我遇到以下代码的问题:

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

然后,当我执行时:

> hugs myprogram.hs
Run Code Online (Sandbox Code Playgroud)

我明白了

Error Instances of (Floating Int, RealFrac Int) required for definition of exactRootList
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误.

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

exactRootList 1 10
Run Code Online (Sandbox Code Playgroud)

它必须回归

1 4 9
Run Code Online (Sandbox Code Playgroud)

因为1到10之间只有1,4和9具有确切的根.

问候!

Tho*_*son 6

如果你看看sqrt你看到它的类型它只适用于以下类型的类型Floating:

> :t sqrt
sqrt :: Floating a => a -> a
Run Code Online (Sandbox Code Playgroud)

您可能知道,Int不是浮点值.您需要使用以下内容转换您的整数(变量x)fromIntegral:

[x | x<-[ini .. end],  let a = fromIntegral x
                       in (floor (sqrt a)) == (ceiling (sqrt a))]
Run Code Online (Sandbox Code Playgroud)