[Haskell-beginners] Show and showList
animeshsaxena at icloud.com
Sat Jan 24 01:21:20 UTC 2015
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."
class Show a where
showsPrec :: Int -> a -> ShowS
show :: a -> String
showList :: [a] -> ShowS
*Main> show [1,2,3]
*Main> show ['a','b','c']
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?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners