Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Ambiguous type variable, why?

Tags:

types

haskell

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?

like image 486
Clinton Avatar asked Apr 17 '13 05:04

Clinton


1 Answers

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])  
like image 74
mightybyte Avatar answered Oct 21 '22 11:10

mightybyte