0
两个元素的列表的末尾到目前为止,我有添加符号方案
(define insert-3
(lambda (sym ls)
(cond
[(null? ls) '()]
[else (cons sym (insert-3 (caadr ls)))])))
我知道caadr是错误的,因为它不会在两个元素的列表中存在。但是我不知道如何在列表的末尾添加一个符号。
两个元素的列表的末尾到目前为止,我有添加符号方案
(define insert-3
(lambda (sym ls)
(cond
[(null? ls) '()]
[else (cons sym (insert-3 (caadr ls)))])))
我知道caadr是错误的,因为它不会在两个元素的列表中存在。但是我不知道如何在列表的末尾添加一个符号。
假设
sym is 'c
ls is '(a b)
那么你的结果将通过
> (cons 'a (cons 'b (list 'c)))
'(a b c)
或等效
> (cons 'a (cons 'b (cons 'c null)))
'(a b c)
所以你的过程需要缺点每个元素,直到它已消耗LS构成,然后在此时使用cons(list sym)或(cons sym null):
(define insert-3
(lambda (sym ls)
(cond
[(null? ls) (list sym)]
[else (cons (car ls) (insert-3 sym (cdr ls)))])))
这样
(insert-3 'c '(a b))
=> (cons 'a (insert-3 'c '(b)))
=> (cons 'a (cons 'b (insert-3 'c '())))
=> (cons 'a (cons 'b (list 'c)))
这将为列表的任何长度工作:
> (insert-3 'c '(a b))
'(a b c)
> (insert-3 'e '(a b c d))
'(a b c d e)
这是一个很简单的功能:
(define (insert-3 sym lst)
(reverse (cons sym (reverse lst))))
这里是另一个
(define (insert-3 sym lst)
(assert (= 2 (length lst)))
(let ((frst (car lst))
(scnd (cadr lst)))
(list frst scnd sym)))
如果你要开始考虑递归,有效率的有点太:
(define (insert-at-end! sym lst)
(if (null? lst)
(list sym)
(let looking ((l lst))
(if (null? (cdr l))
(begin (set-cdr! l (list sym)) ;; replace last `cdr`
lst) ;; return modified `lst`
(looking (cdr l))))))
> (insert-at-end! 1 '(5 4 3 2))
(5 4 3 2 1)
> (insert-at-end! 1 '(2))
(2 1)
> (insert-at-end! 1 '())
(1)