1{-# OPTIONS -fglasgow-exts #-}
2
3module Typecase2 (tests) where
4
5{-
6
7This test provides a variation on typecase1.hs.
8This time, we use generic show as defined for all instances of Data.
9Thereby, we get rid of the Show constraint in our functions.
10So we only keep a single constraint: the one for class Data.
11
12-}
13
14import Test.HUnit
15
16import Data.Generics
17import Data.Maybe
18
19-- Some datatype.
20data MyData = MyCons String deriving (Typeable, Data)
21
22--
23-- Some function that performs type case.
24--
25f :: Data a => a -> String
26f a = (maybe (maybe (maybe others
27              mytys (cast a) )
28              float (cast a) )
29              int   (cast a) )
30
31 where
32
33  -- do something with ints
34  int :: Int -> String
35  int a =  "got an int, incremented: " ++ show (a + 1)
36
37  -- do something with floats
38  float :: Float -> String
39  float a = "got a float, multiplied by .42: " ++ show (a * 0.42)
40
41  -- do something with my data
42  mytys :: MyData -> String
43  mytys a = "got my data: " ++ gshow a
44
45  -- do something with all other data
46  others = "got something else: " ++ gshow a
47
48
49--
50-- Test the type case
51--
52tests = ( f (41::Int)
53        , f (88::Float)
54        , f (MyCons "42")
55        , f True) ~=? output
56
57output = ( "got an int, incremented: 42"
58         , "got a float, multiplied by .42: 36.96"
59         , "got my data: (MyCons \"42\")"
60         , "got something else: (True)")
61
62