Novice Haskell query

Ashley Yakeley [email protected]
Tue, 31 Jul 2001 15:49:22 -0700


At 2001-07-31 14:17, Mark Carroll wrote:

>Now, "show x" will work, and "show y" won't. How can I write things so
>that I can show both x and y? I don't seem to be able to write, say,
>
>  instance Show a => Show (Tree a) where
>      show (Branch datum left right) =
>        show left ++ " <- " ++ show datum ++ " -> " ++ show right
>  
>  instance Show (Tree a) where
>      show Leaf = "*"

These two instances overlap. You want one instance, with both Branch and 
Leaf alternatives in the 'show' function.

>or, perhaps,
>
>  instance Show (Tree a) where
>      Show a => show (Branch datum left right) =
>        show left ++ " <- " ++ show datum ++ " -> " ++ show right
>      show Leaf = "*"

Close, but you're making a promise (that 'Tree a' is Show for _any_ 'a') 
that you can't fulfill. Attempting to restrict the type of 'a' while 
defining the function is bogus, the 'a' symbol simply isn't in scope at 
that point.

Clearly the type 'Tree a' is only Show if 'a' is. It's irrelevant that 
the 'Leaf' part of the definition doesn't need 'a' to be Show: the 
'Branch' part does, so the type has to be restricted to 'Show a => Tree 
a' if it is going to be Show.

So you want this:

instance Show a => Show (Tree a) where
     ...


-- 
Ashley Yakeley, Seattle WA