As an example, consider the trivial function
f :: (Integral b) => a -> b
f x = 3 :: Int
GHC complains that it cannot deduce (b ~ Int). The definition matches the signature in the sense that it returns something that is Integral (namely an Int). Why would/should GHC force me to use a more specific type signature?
Thanks
Type variables in Haskell are universally quantified, so
Integral b => bdoesn’t just mean someIntegraltype, it means anyIntegraltype. In other words, the caller gets to pick which concrete types should be used. Therefore, it is obviously a type error for the function to always return anIntwhen the type signature says I should be able to choose anyIntegraltype, e.g.IntegerorWord64.There are extensions which allow you to use existentially quantified type variables, but they are more cumbersome to work with, since they require a wrapper type (in order to store the type class dictionary). Most of the time, it is best to avoid them. But if you did want to use existential types, it would look something like this:
Code using this function would then have to be polymorphic enough to work with any
Integraltype. We also have to pattern match usingcaseinstead ofletto keep GHC’s brain from exploding.In the above example, you can think of
xas having the typeexists b. Integral b => b, i.e. some unknownIntegraltype.