1{-# OPTIONS -fglasgow-exts #-}
2
3module GShow (tests) where
4
5{-
6
7The generic show example from the 2nd boilerplate paper.
8(There were some typos in the ICFP 2004 paper.)
9Also check out Data.Generics.Text.
10
11-}
12
13import Test.HUnit
14
15import Data.Generics hiding (gshow)
16import Prelude hiding (showString)
17
18
19gshow :: Data a => a -> String
20gshow = gshow_help `extQ` showString
21
22gshow_help :: Data a => a -> String
23gshow_help t
24     =  "("
25     ++ showConstr (toConstr t)
26     ++ concat (intersperse " " (gmapQ gshow t))
27     ++ ")"
28
29showString :: String -> String
30showString s = "\"" ++ concat (map escape s) ++ "\""
31               where
32                 escape '\n' = "\\n"
33                 escape other_char = [other_char]
34
35gshowList :: Data b => [b] -> String
36gshowList xs
37    = "[" ++ concat (intersperse "," (map gshow xs)) ++ "]"
38
39gshow' :: Data a => a -> String
40gshow' = gshow_help `ext1Q` gshowList
41                    `extQ`  showString
42
43intersperse :: a -> [a] -> [a]
44intersperse _ []     = []
45intersperse x [e]    = [e]
46intersperse x (e:es) = (e:(x:intersperse x es))
47
48tests = ( gshow' "foo"
49        , gshow' [True,False]
50        ) ~=? output
51
52output = ("\"foo\"","[(True),(False)]")
53