[Haskell-beginners] Show and showList
Brandon Allbery
allbery.b at gmail.com
Sat Jan 24 01:28:32 UTC 2015
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150123/eb641dfe/attachment.html>
More information about the Beginners
mailing list