到目前为止我有
(define insert-3
(lambda (sym ls)
(cond
[(null? ls) '()]
[else (cons sym (insert-3 (caadr ls)))])))
我知道 caadr 是错误的,因为它不存在于两个元素列表中。但我不知道如何在列表末尾添加符号。
Here is a very simple function:
(define (insert-3 sym lst)
(reverse (cons sym (reverse lst))))
Here is another
(define (insert-3 sym lst)
(assert (= 2 (length lst)))
(let ((frst (car lst))
(scnd (cadr lst)))
(list frst scnd sym)))
If you want to start thinking about recursion, with a little bit of efficiency too:
(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)
假设
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)
因此,您的过程需要对每个元素进行 cons,直到它消耗完 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)