
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

Thanks to everyone who responded. (-: On Tue, 31 Jul 2001, Ashley Yakeley wrote: (snip)
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. (snip)
Ah, right. Yes, I guess partly I was indeed confused because the 'Leaf' part of the definition doesn't need 'a' to be Show - I'd been hoping to be able to define that bit without the "Show a =>" requirement. I see now that this reminds me of a previous thing I'd asked where, say, I define: test [a,b] = a>b test _ = False ...and am then surprised at it complaining when I ask the value of test [] I guess the lesson is that I can't just look at a definition and see that it should be easy for Haskell to evaluate something; it still insists on having enough type information for bits of code that aren't being used, and no doubt I'll get used to it in time and figure out when this extra type information is needed. (-: Thanks! -- Mark
participants (2)
-
Ashley Yakeley
-
Mark Carroll