Victor Aguilar
Victor Aguilar

Reputation: 455

Conversion between Int and fractional values

I am programming in Haskell and I am having trouble with the following code:

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

Then, when I execute:

> hugs myprogram.hs

I get

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

I do not understand this error.

My program should show a list of numbers that have exact root as 4 or 9, on the interval [a, b] where a and b are the two params of the function. Example:

exactRootList 1 10

It must return

1 4 9

Because between 1 and 10 only 1, 4 and 9 have exact root.

Greetings!

Upvotes: 1

Views: 2069

Answers (1)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

If you look at the type of sqrt you see it only works on types that are an instance of Floating:

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

As you probably know, Int is not a floating point value. You need to convert your ints (the variable x) using fromIntegral:

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

Upvotes: 6

Related Questions