In Haskell, I am having some problems defining functions because the types of my argument does not match the required type.
For example, I would like to write a function that takes an n :: Int and produces the list of integers from 1 to the floor of the square root of n. Hence I would to have a function such as:
list :: Int -> [Int]
Originally I defined the function as follows:
list :: Int -> [Int]
list n = [1 .. floor (sqrt n)]
When I loaded the sript, there is an error message of the types not matching. However, I am not sure if I am not matching the type of the sqrt function or the floor function. The error message is the follow:
No instance for (Floating Int)
arising from a use of 'sqrt' at pe142.hs:6:22-27
Possible fix: add an instance declaration for (Floating Int)
In the first argument of 'floor', namely '(sqrt n)'
In the expression: floor (sqrt n)
In the expression: [1 .. floor (sqrt n)]
Failed, modules loaded: none.
Could someone explain to me what is causing the error and how it can be fixed?
sqrtrequires an argument of theFloatingclass, e.g. aDouble. You’re passing it anInt, which is not an instance of theFloatingclass – that’s what the error message is telling you.So to fix the error, convert your
Intto aDoublebefore callingsqrt. You can use thefromIntegralfunction for that.