[Haskell-cafe] ShowList magic

Lennart Augustsson lennart at augustsson.net
Mon May 17 18:13:25 EDT 2010


Your question is actually deeper than some of the people answering you
seem to realize.
How does ghci decide what to do when you say
  show []
?
The expression [] has type [a], which means it could be a list of any
type 'a', including Char.
Normally, when Haskell can't determine the type in this kind of
context it will complain.
You can try compiling the program
  main = putStrLn (show [])
and you'll see the error message.
But in ghci there is a special defaulting rule that will use the type
() ambiguous types.
So ghci will use the 'Show ()' instance, which uses the default
implementation for showList.

  -- Lennart

On Mon, May 17, 2010 at 4:56 AM, Abby Henríquez Tejera
<paradoja at gmail.com> wrote:
> Hi.
>
> I'm a Haskell newbie and there's a bit of Haskell code that I don't
> understand how it works. In the prelude, defining the class Show, the
> function showList is implemented twice, one for String and another one
> for other lists:
>
>    showList cs = showChar '"' . showl cs
>                 where showl ""       = showChar '"'
>                       showl ('"':cs) = showString "\\\"" . showl cs
>                       showl (c:cs)   = showLitChar c . showl cs
>
> and
>
>
>
>    showList []       = showString "[]"
>    showList (x:xs)   = showChar '[' . shows x . showl xs
>                        where showl []     = showChar ']'
>                              showl (x:xs) = showChar ',' . shows x .
>                                             showl xs
>
> The thing is... how does Haskell «know» which to execute? It works
> even for the blank string:
> Prelude> show ""
> "\"\""
> Prelude> show []
> "[]"
>
> Salud,
> Abby
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list