I’m following “Real World Haskell”, and am going through chapter 2, where the exercise is to create a “lastButOne” function which returns the second to last value in the list. My original code was:
lastButOne xs = if null (tail (tail xs))
then head xs
else lastButOne (tail xs)
Which works fine unless I give it a list with only 1 or 2 items. So I modified it to this:
lastButOne xs = if null xs || null (tail xs)
then head xs
else
if null (tail (tail xs))
then head xs
else lastButOne (tail xs)
Which checks if it only has 1 or 2 items, but then fails if it only has 1 item because of the call to head. My problem is that I can’t think of anything else to return other than “head xs”, ideally I want it to return null or something like that, but I can’t find a “null” that allows the function to still be polymorphic.
Perhaps you are looking for a
Maybetype: