diff options
| author | Jan Sucan <jan@jansucan.com> | 2023-03-16 19:44:58 +0100 |
|---|---|---|
| committer | Jan Sucan <jan@jansucan.com> | 2023-03-16 19:44:58 +0100 |
| commit | 82e61723ec378cefd56b5b351340b3d33bc490fc (patch) | |
| tree | 3580ad42ef47990acbf38a36a875a36cfbc5a89c | |
| parent | 95d33cc241ed79f81783002eb7a34fd21cf59161 (diff) | |
4_a_1: Add solution
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | ch04/4_a_1.hs | 64 |
2 files changed, 65 insertions, 1 deletions
@@ -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 |
