/ Haskell / tutorial / type-basics / Types.hs
Types.hs
 1  module Types
 2      where
 3  
 4  data Pair a b = Pair a b
 5  
 6  pairFst (Pair x y) = x
 7  pairSnd (Pair x y) = y
 8  
 9  
10  data Triple a b c = Triple a b c
11  tripleFst (Triple a _ _) = a
12  tripleSnd (Triple _ b _) = b
13  tripleThr (Triple _ _ c) = c
14  
15  
16  data Quad a b = Quad a a b b
17  
18  firstTwo :: Quad a b -> [a]
19  firstTwo (Quad a b _ _) = [a, b]
20  
21  secondTwo :: Quad a b -> [b]
22  secondTwo (Quad _ _ a b) = [a, b]
23  
24  
25  -- Multiple constructors
26  --
27  
28  {-
29   - data Maybe a = Nothing | Just a
30   - 
31   - is defined in Prelude
32   -}
33  firstElement :: [a] -> Maybe a
34  firstElement [] = Nothing
35  firstElement (x : rest) = Just x
36  
37  findElement :: (a -> Bool) -> [a] -> Maybe a
38  findElement predicate [] = Nothing
39  findElement predicate (item : rest) =
40      if predicate item
41          then Just item
42      else findElement predicate rest
43  
44  {-
45   - Tuple exercise
46   -}
47  data Tuple a b c d = Singlet a | Doublet a b | Triplet a b c | Quadruplet a b c d
48  
49  tuple1 (Singlet a) = Just a
50  tuple1 (Doublet a _) = Just a
51  tuple1 (Triplet a _ _) = Just a
52  tuple1 (Quadruplet a _ _ _) = Just a
53  
54  tuple2 (Singlet _) = Nothing
55  tuple2 (Doublet _ b) = Just b
56  tuple2 (Triplet _ b _) = Just b
57  tuple2 (Quadruplet _ b _ _) = Just b
58  
59  tuple3 (Singlet _) = Nothing
60  tuple3 (Doublet _ _) = Nothing
61  tuple3 (Triplet _ _ c) = Just c
62  tuple3 (Quadruplet _ _ c _) = Just c
63  
64  tuple4 (Singlet _) = Nothing
65  tuple4 (Doublet _ _) = Nothing
66  tuple4 (Triplet _ _ _) = Nothing
67  tuple4 (Quadruplet _ _ _ d) = Just d
68  
69  
70  -- Recursive Datatypes
71  --
72  
73  data List a = Nil | Cons a (List a)
74  listLength Nil = 0
75  listLength (Cons item rest) = 1 + listLength rest
76  
77  {-
78   - List exercise
79   -}
80  listHead :: List a -> a
81  listHead (Cons first rest) = first
82  
83  listTail :: List a -> a
84  listTail (Cons last Nil) = last
85  listTail (Cons first rest) = listTail rest
86  
87  listFoldl :: (b -> a -> b) -> b -> List a-> b
88  listFoldl function init Nil = init
89  listFoldl function init (Cons first rest) = listFoldl function (function init first) rest
90  
91  listFoldr :: (a -> b -> b) -> b -> List a-> b
92  listFoldr function init Nil = init
93  listFoldr function init (Cons first rest) = function first (listFoldr function init rest)
94  
95  -- foldl (-) 1 testref == listFoldl (-) 1 testlist == 1
96  -- foldr (-) 1 testref == listFoldr (-) 1 testlist == 5
97  testlist = Cons 2 (Cons (-2) Nil)
98  testref = [2, -2]