
I am trying to understand the concept of overlapping instances. In the book "Real World Haskell" there is an example of showList which avoids overlapping instances. As per my understanding showList is taking the same problem that method "show" would have for overlapping instances. Here's the snippet which explains how it works... "The Show class defines both a show method, which renders one value, and a showList method, which renders a list of values. The default implementation of showList renders a list using square brackets and commas. The instance of Show for [a] is implemented using showList. The instance of Show for Char provides a special implementation of showList that uses double quotes and escapes non-ASCII-printable characters. As a result, if someone applies show to a [Char] value, the implementation of showList will be chosen, and it will correctly render the string using quotes. At least sometimes, then, we can avoid the need for the OverlappingInstances extension with a little bit of lateral thinking." GHC Code class Show a where showsPrec :: Int -> a -> ShowS show :: a -> String showList :: [a] -> ShowS *Main> show [1,2,3] "[1,2,3]" *Main> show ['a','b','c'] "\"abc\"" *Main> 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? -A

On Fri, Jan 23, 2015 at 8:21 PM, Animesh Saxena
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@gmail.com ballbery@sinenomine.net unix, openafs, kerberos, infrastructure, xmonad http://sinenomine.net

Thanks Brandon....this is a very nice subtle distinction!
-Animesh
On Jan 23, 2015, at 05:28 PM, Brandon Allbery
participants (2)
-
Animesh Saxena
-
Brandon Allbery