From dfb5aa8667e2b4278ee3986d8d88df9bf42ae86d Mon Sep 17 00:00:00 2001 From: Jan Sucan Date: Thu, 9 Mar 2023 20:50:05 +0100 Subject: 2_b_2: Add solution --- ch02/2_b_2.hs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 ch02/2_b_2.hs (limited to 'ch02') 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) -- cgit v1.2.3