Why does not this simple Haskell code compile?

3

I'm studying Haskell, and I do not understand why this code does not 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 that the '+' operator is a function with the parameters

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

but Int and Double types are Num instances

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

Thank you!

    
asked by anonymous 01.07.2018 / 01:41

1 answer

4

The (+) method works with any type, but it requires that the two elements be of the same type. When it identifies that the first element is an Int, it infers that the other element will also be. 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 typing rules, the example is exactly the sum function (+). The (+) :: (Num a) => a -> a -> a will be Int -> Int -> Int

Source: link

    
01.07.2018 / 02:36