aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md2
-rw-r--r--ch04/4_a_1.hs64
2 files changed, 65 insertions, 1 deletions
diff --git a/README.md b/README.md
index 012a09f..e330d0f 100644
--- a/README.md
+++ b/README.md
@@ -68,7 +68,7 @@ more visible in the list the first exercise of a group is in bold italics.
| 3_b_10 | yes, in 3_b_9 | | |
| 3_b_11 | yes, in 3_b_9 | | |
| 3_b_12 | yes, in 3_b_9 | | |
-| **_4_a_1_** | | 84 | 4. Functional programming |
+| **_4_a_1_** | yes | 84 | 4. Functional programming |
| 4_a_2 | | | |
| 4_a_3 | | | |
| 4_a_4 | | | |
diff --git a/ch04/4_a_1.hs b/ch04/4_a_1.hs
new file mode 100644
index 0000000..6dfd445
--- /dev/null
+++ b/ch04/4_a_1.hs
@@ -0,0 +1,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