Search code examples
haskellcompiler-errorstypeerrorfunction-declaration

Why am I recieving a type error?


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?


Solution

  • sqrt requires an argument of the Floating class, e.g. a Double. You're passing it an Int, which is not an instance of the Floating class - that's what the error message is telling you.

    So to fix the error, convert your Int to a Double before calling sqrt. You can use the fromIntegral function for that.