我一直在研究常见的lisp,我已经阅读了示例和一些pdf,我的教授为作业分配了几个问题,我只能使用cons,append,list,equal,defun,car,cdr,cond之一。是要删除特定数量的列表,例如(remove 2 '(1 2 3 4)
,结果:(1 3 4)
,我的代码:
(define (delete ele listx )
(cond ( null? listx)
'( ))
( ( equal? ele (car listx))
(delete ele (cdr listx)))
(else
(cons (car listx)
(delete ele (cdr listx))))))
这并不难,但是现在我必须创建一个删除两个元素之间的函数,例如-> (delete'(a b c d e f) 2 5)
;在第三和第四(a b e f)之间删除
我还没有尝试过任何东西,只是进行了研究,我开始编写一些代码,但是不确定
( defun deletemiddle (index1 index2 listx)
(cond (( null listx) 0 )
(( = valor1 (1) )
((cons (car listx)
答案 0 :(得分:1)
递归时,列表的cdr和两个索引都递减1。
答案 1 :(得分:0)
这里有其他痕迹,可以帮助找出如何递归构建结果列表:
0: (DEL (1 2 3 4 5 6) 2 5)
1: (DEL (2 3 4 5 6) 1 4)
2: (DEL (3 4 5 6) 0 3)
3: (DEL (4 5 6) 0 2)
4: (DEL (5 6) 0 1)
4: DEL returned (5 6)
3: DEL returned (5 6)
2: DEL returned (5 6)
1: DEL returned (2 5 6)
0: DEL returned (1 2 5 6)
0: (DEL (1 2 3 4 5 6) 2 8)
1: (DEL (2 3 4 5 6) 1 7)
2: (DEL (3 4 5 6) 0 6)
3: (DEL (4 5 6) 0 5)
4: (DEL (5 6) 0 4)
5: (DEL (6) 0 3)
6: (DEL NIL 0 2)
6: DEL returned NIL
5: DEL returned NIL
4: DEL returned NIL
3: DEL returned NIL
2: DEL returned NIL
1: DEL returned (2)
0: DEL returned (1 2)
0: (DEL (1 2 3 4 5 6) 0 3)
1: (DEL (2 3 4 5 6) 0 2)
2: (DEL (3 4 5 6) 0 1)
2: DEL returned (3 4 5 6)
1: DEL returned (3 4 5 6)
0: DEL returned (3 4 5 6)
答案 2 :(得分:0)
(defun deletemiddle (list idx1 idx2 &optional (curr 0))
(cond ((null list) '())
((< idx1 curr idx2)
(deletemiddle (cdr list) idx1 idx2 (1+ curr)))
(t (cons (car list)
(deletemiddle (cdr list) idx1 idx2 (1+ curr))))))
;; (< idx1 curr idx2) is short for: (and (> curr idx1) (< curr idx2))
(deletemiddle '(a b c d e f) 2 5)
;; => (A B C F)
尾部递归
(defun deletemiddle (list idx1 idx2 &optional (acc '()))
(cond ((null list) (nreverse acc))
((and (<= idx1 -1) (> idx2 0))
(deletemiddle (cdr list) (1- idx1) (1- idx2) acc))
(t
(deletemiddle (cdr list) (1- idx1) (1- idx2) (cons (car list) acc))))))
(deletemiddle '(a b c d e f) 2 5)
;; => (A B C F)