Strange behaviour with classes (both Hugs and GHC)
Magnus Björk <[email protected]> Mon, 29 May 2006 12:34:02 +0200 (MEST)
| Newsgroups | gmane.comp.lang.haskell.glasgow.bugs,gmane.comp.lang.haskell.hugs.bugs |
|---|---|
| Message-ID | <[email protected]> |
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 _______________________________________________ Glasgow-haskell-bugs mailing list [email protected] http://www.haskell.org/mailman/listinfo/glasgow-haskell-bugs
default-bug.hs
(text/plain, 1.7 KB)
-----------------------------------------------------------------------------
-- 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
}