Why doesn’t this simple code in Haskell compile?

Asked

Viewed 54 times

3

I’m studying Haskell, and I don’t understand why this code doesn’t compile:

foo :: Int -> Double -> Double
foo a b = a+b

The error message is:

Couldn't match expected type `Double' with actual type `Int'
In the first argument of `(+)', namely `a'
In the expression: a + b
In an equation for `foo': foo a b = a + b

I know the operator '+' is a function with the parameters

(+) :: (Num a) => a -> a -> a

but Int and Double types are instances of Num.

So, why does the compiler not accept this code??

Thank you very much!

  • 1

    There are no instances in functional languages in the same way as in procedural languages; Num is a class in the sense that there are types that belong to it, but it does not mean that they are equivalent.

1 answer

4


The (+) method works with any type, but it requires the two elements to be of the same type. When he identifies that the first element is an Int, he infers that the other will be as well. For its addition to work, it is necessary to convert the elements to the same type.

This is due to Monomorphism Restriction, when you do not specify the type, it will infer the types using standard typification rules, the example is exactly the sum function (+). The (+) :: (Num a) => a -> a -> a , will stay Int -> Int -> Int

Source: https://stackoverflow.com/a/8262122/9916784

  • 1

    Amended as requested.

  • 2

    You can leave the link tb as complete, it looks nice jewelry with the main here and the most complete there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.