我的计算机科学作业需要帮助。我一直试图返回列表的最后一个元素,但我一直都在失败。这就是我到目前为止所做的:
(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!"]
[]))
我不知道从哪里开始。我知道我错过了一个基本案例,但我无法弄清楚。请帮忙!
答案 0 :(得分:3)
last
程序已包含在Racket中,您无需实现它。但是如果你必须从头开始编写它,那么在列表结束之前知道哪里停止就是一件简单的事情!像这样:
(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