[Haskell-beginners] Show and showList
animeshsaxena at icloud.com
Sun Jan 25 04:01:03 UTC 2015
Thanks Brandon....this is a very nice subtle distinction!
On Jan 23, 2015, at 05:28 PM, Brandon Allbery <allbery.b at gmail.com> wrote:
On Fri, Jan 23, 2015 at 8:21 PM, Animesh Saxena <animeshsaxena at icloud.com> wrote:
It's the same problem now transfered to showList which will be declared differently for a list of int's or a list of chars, but still it outputs them differently as can be seen from the above code. How it is able to differentiate without throwing up the overlap error?
The key is that showList is defined on e.g. Int or Char, not [Int] or [Char]. If we tried to do the "obvious" thing for a list, we'd define
instance Show a => Show [a] where ...
but then we have an overlap any time we try to define a different handler for a specific list of things (in this case, instance Show [Char] would be the overlapping instance we'd want, to produce the String representation). We avoid this by building the representation for lists into the representation for single items (thus, a showList method); we can provide a default implementation of that method in the Show class to do the usual brackets-and-commas representation, using the mechanism intended to allow optimized versions of typeclass methods for particular types, and then provide a specific implementation for instance Show Char without invoking overlap.
brandon s allbery kf8nh sine nomine associates
allbery.b at gmail.com ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net
Beginners mailing list
Beginners at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners