1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
-- Write your own "safe" definitions of the standard partial list functions, but
-- make sure that yours never fail. As a hint, you might want to consider using
-- the following types.
--
-- -- file: ch04/ch04.exercises.hs
-- safeHead :: [a] -> Maybe a
-- safeTail :: [a] -> Maybe [a]
-- safeLast :: [a] -> Maybe a
-- safeInit :: [a] -> Maybe [a]
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead xs = Just (head xs)
-- ghci> :l 4_a_1.hs
-- [1 of 1] Compiling Main ( 4_a_1.hs, interpreted )
-- Ok, one module loaded.
-- ghci> head [1, 2, 3]
-- 1
-- ghci> head []
-- *** Exception: Prelude.head: empty list
-- ghci> safeHead [1, 2, 3]
-- Just 1
-- ghci> safeHead []
-- Nothing
safeTail :: [a] -> Maybe [a]
safeTail [] = Nothing
safeTail xs = Just (tail xs)
-- ghci> tail [1, 2, 3]
-- [2,3]
-- ghci> tail []
-- *** Exception: Prelude.tail: empty list
-- ghci> safeTail [1, 2, 3]
-- Just [2,3]
-- ghci> safeTail []
-- Nothing
safeLast :: [a] -> Maybe a
safeLast [] = Nothing
safeLast xs = Just (last xs)
-- ghci> last [1, 2, 3]
-- 3
-- ghci> last []
-- *** Exception: Prelude.last: empty list
-- ghci> safeLast [1, 2, 3]
-- Just 3
-- ghci> safeLast []
-- Nothing
safeInit :: [a] -> Maybe [a]
safeInit [] = Nothing
safeInit xs = Just (init xs)
-- ghci> init [1, 2, 3]
-- [1,2]
-- ghci> init []
-- *** Exception: Prelude.init: empty list
-- ghci> safeInit [1, 2, 3]
-- Just [1,2]
-- ghci> safeInit []
-- Nothing
|