我遇到多级递归问题。我有两个号码n1
和n2
。当counter
介于n1
和n2
之间时,我希望结果中包含数字,保持列表内部结构。
(defun izdvoj (lista n1 n2 counter)
(cond ((null lista) counter)
((and (atom (car lista))
(< counter n1)
(izdvoj (cdr lista) n1 n2 (+ counter 1))))
((and (atom (car lista))
(> counter n2)
(izdvoj (cdr lista) n1 n2 (+ counter 1))))
((atom (car lista))
(cons (car lista) (izdvoj (cdr lista) n1 n2 (+ counter 1))))
(t
(cons (izdvoj (car lista) n1 n2 counter) (izdvoj (cdr lista) n1 n2 counter)))))
(izdvoj '(1 2 (3 (4) 5 (6 (7)))(8 (9 (10 ((11))) 12)) (13 ((14) (15)))) 7 13 0)
结果应为((((7))) (8 (9 (10 ((11))) 12)) (13))
我得到(((4) ((7))) (((((11))) 12)) (((14) (15))))
有什么建议吗?
答案 0 :(得分:0)
最简单的方法是返回索引以及帮助程序中的结果。这样,您知道如何在完成car
并准备好cdr
之后继续:
(defun get-range (list from-index to-index)
(labels ((aux (list cur acc)
(cond ((null list)
(values (nreverse acc) cur))
((not (atom (car list)))
(multiple-value-bind (res cur)
(aux (car list) cur '())
(aux (cdr list) cur (cons res acc))))
((<= from-index cur to-index)
(aux (cdr list) (1+ cur) (cons (car list) acc)))
(t (aux (cdr list) (1+ cur) acc)))))
(nth-value 0 (aux list 1 '()))))
(get-range '(a b (c d (e (f))) (g h)) 3 5)
; ==> ((c d (e ())) ())