Learning how to define the type of a function


#1

Hi everyone, I already read how to define a function and its type. I know that this is just a trivial example and that’s why I’m starting with it

intoint :: (Integral a) => a -> Int
intoint x = x :: Int


#2
x :: Int

helps to resolve ambigious types. In some situations the compiler can’t infer the exact type of a variable and you can specify the type, with x :: Int for example, explicitly.
But in your code you have a different situation. You have some a which is an Integral and you’re trying to convert it into Int which cannot be done automatically since Integral a is more generic than Int. The function you’re looking for is fromIntegral:

fromIntegral :: (Integral a, Num b) => a -> b

So it takes an Integral and returns a Num (and Int has an instance of Num).

So you can write:

intoint :: (Integral a) => a -> Int
intoint x = fromIntegral x

or just:

intoint :: (Integral a) => a -> Int
intoint = fromIntegral

Edit: You probably wanted to “cast” to Int. It is not what :: is for. I don’t think Haskell has casts (at least a special syntax for that, after all Haskell is strongly typed :)) like many other languages, but there functions like fromIntegral that do similar conversions.