]> gitweb.michael.orlitzky.com - dead/harbl.git/blob - src/Pretty.hs
14911246c8cd801a7f38b16aaef7a672e4c30bba
[dead/harbl.git] / src / Pretty.hs
1 {-# LANGUAGE FlexibleInstances #-}
2
3 -- | A typeclass for pretty-printing. Types that wish to be
4 -- pretty-printed should make themselves an instance of the 'Pretty'
5 -- class. The only class function that they need to implement is
6 -- 'pretty_show', which turns the thing into a string in a nice
7 -- way. The 'pretty_print' function then prints the result of
8 -- 'pretty_show' by default.
9 --
10 module Pretty ( Pretty(..) )
11 where
12
13 import Text.Parsec ( ParseError )
14
15
16 class Pretty a where
17 -- | Obtain a pretty 'String' representation of the given thingy.
18 pretty_show :: a -> String
19
20 -- | Pretty-print the given thingy.
21 pretty_print :: a -> IO ()
22 pretty_print = putStrLn . pretty_show
23
24
25 -- | If we can pretty print something, we can pretty-print a list of
26 -- them too.
27 --
28 instance (Pretty a) => Pretty [a] where
29 pretty_show l = show $ map pretty_show l
30
31
32 -- | If we can pretty print something, we can pretty-print a pair of
33 -- them too.
34 --
35 instance (Pretty a, Pretty b) => Pretty (a,b) where
36 pretty_show (x,y) = show (pretty_show x, pretty_show y)
37
38
39
40 -- | Define a 'Pretty' instance for the result of 'parse'. This lets
41 -- us pretty-print the result of a parse attempt without worrying
42 -- about whether or not it failed. If the parse failed, you get the
43 -- same output that you usually would. Otherwise we pretty-print the
44 -- parsed value.
45 --
46 instance Pretty a => Pretty (Either ParseError a) where
47 pretty_show (Left err) = show err
48 pretty_show (Right v) = pretty_show v