Strange error in show for datatype

Bjorn Lisper lisper@it.kth.se
Wed, 3 Oct 2001 16:43:57 +0200 (MET DST)


Hi,

For a change, a teacher asking for help on behalf of a student....

I have a student who wants to emulate S-expressions of Lisp in Haskell. He
came up with the following data type:

data LispList t = Atom t | LispList [LispList t] | Str [Char]

This works just fine. He then wanted to make it an instance of Show, in
order to print values of this type:

instance Show t => Show (LispList t) where
    show (Atom t) = show t
    show (LispList t) = show t
    show (Str t) = show t

Now, this compiles and works for some values of the type, but not for all!
Here is what happens in hugs:

hugsprompt>  (Atom 1) ==> 1
hugsprompt>  (LispList [Atom 1, Str "HEJ"]) ==> [1,"HEJ"]
hugsprompt>  (LispList [Atom 1, LispList [Str "HEJ"]]) ==> [1, ["HEJ"]]
hugsprompt>  (Str "HEJ") ==> "Cannot find show function...."
hugsprompt>  (LispList [Str "HEJ"]) ==> "Cannot find show function...."
hugsprompt>  (LispList [Str "HEJ",Atom 1]) ==> "Cannot find show function...."

So there is a problem when the value is of form Str string or where such a
value is first in the list l in a value of the form LispList l. Oddly
enough, such values may appear at other positions without causing any
problems.

I don't think there is a bug in hugs. Similar problems appear if the Show
instance is derived, and ghc will also complain - if the definition
f = show (LispList [Str "HEJ"])
is compiled, for instance, the compiler will complain about ambiguous
contexts. Ghc will say

Enrico.hs:1: Ambiguous context `{Show taKi}'
                 `Show taKi' arising from use of `show' at Enrico.hs:17

and hugs

Reading file "Enrico.hs":
Type checking      
ERROR "Enrico.hs" (line 17): Unresolved top-level overloading
*** Binding             : f
*** Outstanding context : Show b

So I wonder whether the infamous Monomorphism Restriction is lurking
somewhere here? But I cannot see exactly how right now. Does anyone else
have a clue?

Björn