Strange behaviour with classes (both Hugs and GHC)

Magnus Björk mab at cs.chalmers.se
Mon May 29 06:34:02 EDT 2006


I just ran into a strange behaviour of both Hugs and GHC. I discussed it 
with John Hughes who managed to find a workaround, and suggested that I 
ask you whether this is really expected behaviour.

The attached file contains a small example that exhibits the problem.

-- 
/MpB
-------------- next part --------------
-----------------------------------------------------------------------------
-- Class Default - used to define default values for types

class Default a where
  defaultVal :: a

instance Default () where
  defaultVal = ()

instance Default Bool where
  defaultVal = False

instance Default Int where
  defaultVal = 0

-----------------------------------------------------------------------------
-- Data type with annotations

data MyAnnotatedType a = MAT { theInt :: Int
			     , theBool :: Bool
			     , theAnnotation :: a 
			     }

-- If the annotation type a is an instance of default, the we can define
-- default values for MyAnnotatedType a:

instance Default a => Default (MyAnnotatedType a) where
  defaultVal = MAT defaultVal defaultVal defaultVal

-----------------------------------------------------------------------------
-- Defining values of MyAnnotatedType (this is where we run into problems)

noProblem :: MyAnnotatedType ()
noProblem = defaultVal { theInt = 42 }

noProblem2 :: MyAnnotatedType Int
noProblem2 = defaultVal { theInt = 42 }

problematic :: MyAnnotatedType Int
problematic = defaultVal { theInt = 42
			 , theAnnotation = 10 
			 }

-- The line ", theAnnotation = 10" is the problematic one. It seems impossible
-- to fix the problem by rewriting this line (I've tried things such as 
-- defaultVal, error "", or adding the type explicitly). 

-----------------------------------------------------------------------------
-- A workaround (thanks to John Hughes)

-- define an unoverloaded version of defaultVal
defaultMAT = defaultVal :: MyAnnotatedType Int

workaround :: MyAnnotatedType Int
workaround = defaultMAT { theInt = 42
			, theAnnotation = 10
			}





More information about the Glasgow-haskell-bugs mailing list