lastButOne xs = if null xs
then 0
else xs !! ((length xs) - 2)
I am reading Chapter 2. Types and Functions . I am doing one of their challenge questions and was asked to get the second to last item in a list.
My solution was the code attached. I don’t know what to return if a list is empty. Should I throw an error. if the list I pass in is empty.
I also noticed I recieved an error message of
• Non type-variable argument in the constraint: Num [a]
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a. Num [a] => [a]
When I returned 2 different types from the function. What does the error mean ?
I produced this solution with the code below.
lastButOne xs = if null xs
then xs
else xs !! ((length xs) - 2)