树/列表的递归算法通常用COND
编写。你弄清楚结局条件是什么,然后把它放在第一位。然后处理原子,最后遍历一个列表,递归调用其CAR
和CDR
和CONS
上的函数来生成输出列表。所以基本的模板是这样的:
(defun algo (list)
(cond
((end-condition) suitable-end-value)
((atom list) (do-something-with-atom list))
(t (cons (algo (car list)
(algo (cdr list))))))
在这种情况下,这将是这样的:
(defun rhythm-tree (n tree)
(cond ((zerop n) tree) ; First end-condition.
((null tree) '()) ; Another end-condition.
((atom tree) ; An atom: transform into...
(cons tree ; a list of the atom itself...
(list (rhythm-tree (1- n) ; and a list of children.
(case tree
(1 (list 1 2))
(2 (list 1))
(otherwise '()))))))
;; Iterate over elements of a list.
(t (cons (rhythm-tree n (car tree))
(rhythm-tree n (cdr tree))))))
(rhythm-tree 1 1)
;=> (1 (1 2))
(rhythm-tree 2 1)
;=> (1 ((1 (1 2)) (2 (1))))
那么,要问什么?请记住,这不是一个代码写作服务;) –
你是对的@Daniel问题是:我如何递归定义这个行为?答案可以是纯英文的,所以没有代码服务。我不知道从哪里开始。我甚至不需要一个答案,只是向正确的方向推动就足够了。 – kureta
@kureta你可以尝试解释一下这个问题好一点吗?也许增加一些函数调用的例子,它们的结果以及结果是如何达到的(基本上写出你希望计算机执行的过程)。就像现在一样,至少我无法弄清楚你想要什么。我的意思是,你从'(1)'开始。根据第一条规则,这变成了“(1 2)”。 (1 2)'没有变换规则,那么你怎样才能得到'(1(1 2))'?原子中的原子是否也应该被转换(但是你会有'((1 2)(1))')? – jkiiski