1{-# OPTIONS -fglasgow-exts #-} 2 3module Typecase1 (tests) where 4 5{- 6 7This test demonstrates type case as it lives in Data.Typeable. 8We define a function f that converts typeables into strings in some way. 9Note: we only need Data.Typeable. Say: Dynamics are NOT involved. 10 11-} 12 13import Test.HUnit 14 15import Data.Typeable 16import Data.Maybe 17 18-- Some datatype. 19data MyTypeable = MyCons String deriving (Show, Typeable) 20 21-- 22-- Some function that performs type case. 23-- 24f :: (Show a, Typeable a) => a -> String 25f a = (maybe (maybe (maybe others 26 mytys (cast a) ) 27 float (cast a) ) 28 int (cast a) ) 29 30 where 31 32 -- do something with ints 33 int :: Int -> String 34 int a = "got an int, incremented: " ++ show (a + 1) 35 36 -- do something with floats 37 float :: Float -> String 38 float a = "got a float, multiplied by .42: " ++ show (a * 0.42) 39 40 -- do something with my typeables 41 mytys :: MyTypeable -> String 42 mytys a = "got a term: " ++ show a 43 44 -- do something with all other typeables 45 others = "got something else: " ++ show a 46 47 48-- 49-- Test the type case 50-- 51tests = ( f (41::Int) 52 , f (88::Float) 53 , f (MyCons "42") 54 , f True) ~=? output 55 56output = ( "got an int, incremented: 42" 57 , "got a float, multiplied by .42: 36.96" 58 , "got a term: MyCons \"42\"" 59 , "got something else: True")