且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除列表的最后一个元素(方案)

更新时间:2023-11-10 08:18:52

您写道:反向,汽车,反向".我相信你的意思是写反向,cdr,反向".这个解决方案没有任何问题;它与列表的大小呈线性关系,就像使用标准列表的任何解决方案一样.

You wrote: "reverse, car, reverse". I believe you meant to write "reverse, cdr, reverse". There's nothing wrong with this solution; it's linear in the size of the list, just like any solution to this that uses the standard lists.

作为代码:

;; all-but-last: return the list, not including the last element
;; list? -> list?
(define (all-but-last l) (reverse (cdr (reverse l))))

如果列表的多次遍历或另一个列表副本的不必要构造困扰你,你当然可以通过直接写东西来避免它.

If the multiple traversal of the list or the needless construction of another list copy bothers you, you can certainly avoid it, by writing the thing directly.

考虑到你的几乎解决方案,我假设这不是家庭作业.

Given your almost-solution, I'm going to assume that this isn't homework.

这是球拍的样子:

#lang racket

(require rackunit)

;; all-but-last : return the list, except for the last element
;; non-empty-list? -> list?
(define (all-but-last l)
  (cond [(empty? l) (error 'all-but-last "empty list")]
        [(empty? (rest l)) empty]
        [else (cons (first l) (all-but-last (rest l)))]))

(check-equal? (all-but-last '(3 4 5))
              '(3 4))