Scheme将元素添加到列表末尾

时间:2012-10-04 01:26:07

标签: scheme racket

如何在列表末尾添加元素(在空前) 只有缺点,首先,休息,空?和cond递归可以使用

2 个答案:

答案 0 :(得分:6)

考虑一下如何实现append(或者更一般地,考虑如何实现右侧折叠)。现在,如果将列表附加到包含要添加的元素的单例列表中,则基本上会附加元素。

(显然,这是O(n),所以不要以这种方式单独添加元素。)


这是使用右折叠的解决方案:

(define (append-element lst elem)
  (foldr cons (list elem) lst))

以及使用append的解决方案:

(define (append-element lst elem)
  (append lst (list elem)))

因此,如果您可以自己实施foldrappend,请使用您列出的操作(这很容易!尝试一下),您就可以了。

P.S。实际上,您可以使用右侧折叠实现append

(define (append lst1 lst2)
  (foldr cons lst2 lst1))

但这仍然让您自己实施foldr。 ;-)(提示:这很简单。请查看my implementation of left-fold以获取创意。)

答案 1 :(得分:3)

这看起来像是家庭作业,所以我会给你一些指示,让你正确的轨道,填补空白:

(define (add-last lst ele)
  (cond ((empty? lst)    ; if the list is empty
         <???>)          ; create a one-element list with `ele`
        (else            ; if the list is non-empty
         (cons <???>     ; cons the first element in the list
               <???>)))) ; with the result of advancing the recursion

以上内容可以consfirstrestempty?cond来实施,不需要其他程序。

相关问题