I need help with my computer science homework. I've been trying to return the last element of a list but I keep failing. This is what I have so far:
(check-expect (last empty) "Error! The list is empty!")
(check-expect (last (list "apple" "banana" "pear" "orange")) "orange")
(define (last loe)
(cond
[(empty? loe) "Error! The list is empty!"]
[]))
I do not know where to go from here. I know i am missing a base case but i cannot figure it out. please help!
The last
procedure is already included in Racket, you don't need to implement it. But if you have to write it from scratch it's a simple matter of knowing where to stop - right before the list ends! like this:
(define (last loe)
(cond
[(empty? loe) "Error! The list is empty!"] ; we don't allow empty lists
[(empty? (rest loe)) (first loe)] ; stop right before last
[else (last (rest loe))])) ; advance recursion