aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md2
-rw-r--r--ch02/2_b_2.hs20
2 files changed, 21 insertions, 1 deletions
diff --git a/README.md b/README.md
index 743333c..ee77124 100644
--- a/README.md
+++ b/README.md
@@ -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)