[Haskell] A puzzle and an annoying feature

Lennart Augustsson lennart at augustsson.net
Wed Nov 24 16:25:38 EST 2004

Here is a small puzzle.

-- The following generates a type error:
f :: Char -> Char
f c =
     let x = g c
     in  h x

-- But this definition does not:
f :: Char -> Char
f c =
     let x :: Bool
	x = g c
     in  h x

Furthermore, replacing Bool by any other type in the
latter definition will always give a type error.

How is this possible?

Scroll down for the answer.

Here is the module:

module Puzzle(f) where

f :: Char -> Char
f c =
     let x = g c
     in  h x

class C a where
     g :: Char -> a
     h :: a -> Char

instance C Bool where
     g c = c == 'T'
     h b = if b then 'T' else 'F'

The error message from ghc is
     Ambiguous type variable `a' in the top-level constraint:
       `C a' arising from use of `g' at Puzzle.hs:5:12

I know the technical reason why this is happening.
But it's hard for me to motivate why this is reasonable.
The type variable `a' is not ambiguous at all, the only
type it can possibly have is Bool; any other type is an error.

Furthermore, there can never be any other instance of the
class C added to any program using the module Puzzle since
the class C is not exported.

So in what sense is this really ambiguous?

I think it would be quite reasonable to allow the Puzzle module
to compile, resolving `a' to be Bool.  I.e., if there is only one
instance that can satisfy a constraint and there is no possibility
of adding instances outside the compiled module, I think resolving the
overloading makes sense.

	-- Lennart

More information about the Haskell mailing list