diff options
| author | Jan Sucan <jan@jansucan.com> | 2023-03-09 20:50:05 +0100 |
|---|---|---|
| committer | Jan Sucan <jan@jansucan.com> | 2023-03-09 20:50:05 +0100 |
| commit | dfb5aa8667e2b4278ee3986d8d88df9bf42ae86d (patch) | |
| tree | 81c5d8b8a7f417d2095d8ea38f74c4131e977266 | |
| parent | fe4b4262e0d62b454c91d99a8c9cd4568fdd49d1 (diff) | |
2_b_2: Add solution
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | ch02/2_b_2.hs | 20 |
2 files changed, 21 insertions, 1 deletions
@@ -49,7 +49,7 @@ more visible in the list the first exercise of a group is in bold italics. | 1_a_4 | yes | | | | **_2_a_1_** | yes | 25 | 2. Types and functions | | **_2_b_1_** | yes | 39 | | -| 2_b_2 | | | | +| 2_b_2 | yes | | | | 2_b_3 | | | | | **_3_a_1_** | | 60 | 3. Defining types, streamlining functions | | 3_a_2 | | | | diff --git a/ch02/2_b_2.hs b/ch02/2_b_2.hs new file mode 100644 index 0000000..921e811 --- /dev/null +++ b/ch02/2_b_2.hs @@ -0,0 +1,20 @@ +-- Write a function lastButOne, that returns the element before the last. + +-- This function is written in a bit cumbersome way. This is because we have +-- avoided using functions introduced in later chapters of the book (e.g., +-- length, pattern matching). The myDrop function has been used as an example. +-- +-- This function expects a list of at least two elements so the element before +-- the last one always exists. +-- +-- Checking the length of the list deserves some explanation. A call to tail +-- discards the first element from the list. It is like subtracting 1 from the +-- length of the list. Let's have a list of length N. If a list of length N - 2 +-- (two calls to tail) is not empty, then N is greater or equal to 3. If it is +-- empty, then N has to be 2. It should not be less than 2 because that is a +-- minimum length of the list expected. + +lastButOne :: [a] -> a +lastButOne xs = if null (tail (tail xs)) -- Check if xs is 2 elements long + then head xs + else lastButOne (tail xs) |
