module Example5 where data AType = Ctr1 Int Int | Ctr2 Char Int Int | Ctr3 (Char, Int) [Char] deriving (Show, Eq, Ord) foo (Ctr1 x y) = x + y foo (Ctr2 _ x y) = x + y foo (Ctr3 (_, x) xs) = x + length xs ------------------------------------------------------------------------------ -- Some predefined types -- data Either a b = Left a | Right b -- data Maybe a = Nothing | Just a -- data [a] = [] | a : [a] -- But this is not quite legal Haskell. my_map :: (a -> b) -> [a] -> [b] my_map f [] = [] my_map f (x : xs) = f x : my_map f xs -- Aside: Mutual reursion. strangeMap :: (a -> b) -> (a -> b) -> [a] -> [b] strangeMap f g [] = [] strangeMap f g (x : xs) = f x : strangeMap' f g xs strangeMap' :: (a -> b) -> (a -> b) -> [a] -> [b] strangeMap' f g [] = [] strangeMap' f g (x : xs) = g x : strangeMap f g xs -- Another way (note how f & g scope over the local defs.): strangeMap2 :: (a -> b) -> (a -> b) -> [a] -> [b] strangeMap2 f g xs = smHlp xs where smHlp [] = [] smHlp (x:xs) = f x : smHlp' xs smHlp' [] = [] smHlp' (x:xs) = g x : smHlp xs ------------------------------------------------------------------------------ -- Tree type. data Tree a = Leaf a | (Tree a) :^: (Tree a) sumTree (Leaf x) = x sumTree (l :^: r) = sumTree l + sumTree r