Why does the following compile:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
class IsList a where
isList :: a -> Bool
instance IsList a where
isList x = False
instance IsList [a] where
isList x = True
main = print (isList 'a') >> print (isList ['a'])
But changing main
to this:
main = print (isList 42) >> print (isList [42])
Gives the following error:
Ambiguous type variable `a0' in the constraints:
(Num a0) arising from the literal `42' at prog.hs:13:22-23
(IsList a0) arising from a use of `isList' at prog.hs:13:15-20
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `isList', namely `42'
In the first argument of `print', namely `(isList 42)'
In the first argument of `(>>)', namely `print (isList 42)'
isList
surely isn't in the Num
class is it? And if not, why the ambiguity?
The issue is not with isList but with the constant 42. The constant 'a' has a concrete type of Char. The constant 42 does not have a concrete type.
ghci> :t 42
42 :: Num a => a
The compiler needs a concrete type. It will work if you change main to the following:
main = print (isList (42 :: Int)) >> print (isList [42 :: Int])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With