13

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?

1 Answer 1

16

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])  
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, thanks, that makes sense. It can compile if it doesn't know its type. But why doesn't "defaulting" work here? Why not default to Integer?
The compiler doesn't have anything indicating that it should treat that as an Int. If the same identifier was...say...passed into a function that needed an Int, then the type would be unified to Int. But it's not going to make that assumption for you automatically.
@Clinton: Defaulting is only done if all the constraints only refer to standard classes. IsList is not a standard class. This requirement can be relaxed with ExtendedDefaultRules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.