aboutsummaryrefslogtreecommitdiff
path: root/ch04/4_a_1.hs
diff options
context:
space:
mode:
authorJan Sucan <jan@jansucan.com>2023-03-16 19:44:58 +0100
committerJan Sucan <jan@jansucan.com>2023-03-16 19:44:58 +0100
commit82e61723ec378cefd56b5b351340b3d33bc490fc (patch)
tree3580ad42ef47990acbf38a36a875a36cfbc5a89c /ch04/4_a_1.hs
parent95d33cc241ed79f81783002eb7a34fd21cf59161 (diff)
4_a_1: Add solution
Diffstat (limited to 'ch04/4_a_1.hs')
-rw-r--r--ch04/4_a_1.hs64
1 files changed, 64 insertions, 0 deletions
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