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 /ch02/2_b_2.hs | |
| parent | fe4b4262e0d62b454c91d99a8c9cd4568fdd49d1 (diff) | |
2_b_2: Add solution
Diffstat (limited to 'ch02/2_b_2.hs')
| -rw-r--r-- | ch02/2_b_2.hs | 20 |
1 files changed, 20 insertions, 0 deletions
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) |
