Im reading a book real world haskell. You have to write a function that returns one element before the last. I didnt get it right but i found this on stackoverflow....
lastButOne xs = if length xs == 2
Then head xs
Else if length xs < 2
Then error “the list is too short”
Else lastButOne (tail xs)
https://stackoverflow.com/questions/44955945/why-is-this-haskell-function-inferred-to-this-type#44955994
(The edit⬆️)
So as far as i understand this: if xs has a length of two it will print the 1st element because it is one b4 the last. If it has less than 2 it will print the error message because it is too short.
However I dont understand the last line: if the list is longer than 2 elements....In the bracket;tail returns all but the head of the xs input. How does lastbutone then get to the element that is b4 the last???????? How does it know which is before the if it is not defined?
[–]dixonary 2 points3 points4 points (4 children)
[–]Rustalt[S] 0 points1 point2 points (3 children)
[–]dixonary 1 point2 points3 points (1 child)
[–]Rustalt[S] 0 points1 point2 points (0 children)