Reputation: 37
I have this function lastList that is suppose to call the last element of a list. I need to do manually, without predefined "last" in Prelude. I have this code so far
lastList :: List a -> a
lastList list = case list of
Empty -> error "List is empty"
Cons _ xs -> lastList xs
It gives me an output "List is empty" with the list
test3 :: List Double
test3 = Cons 1.3 (Cons 5.2 (Cons 3.0 (Cons 8.7 (Cons 9.1 Empty))))
What is the problem? Thank you
Upvotes: 1
Views: 111
Reputation: 477437
The problem: you only define Empty
as basecase, which will error. So every non-infinite list, will eventually result in the Empty
basecase, and error. Infinite lists will loop forever, but that is something we can not circumvent since infinite lists simply have no last element.
Since the List
is a linked list with a head
(which is an element) and a tail
(which is the rest of the list) as Cons head tail
and a Empty
, a list with one element is thus Cons x Empty
. So that means in case we obtain such a pattern, we should return x
.
Furthermore in case the tail
is not Empty
, we should perform recursion on the tail, until we obtain a list with only one element left.
In case the list is Empty
, the list is empty, and thus we should error on this input.
lastList :: List a -> a
lastList Empty = error "List is empty"
lastList (Cons x Empty) = x
lastList (Cons _ xs) = lastList xs
Upvotes: 6