也许一些带有注释的代码会有所启发。
通过递归,我们可以通过一个列表进行迭代。例如,我们可以构建一个简单的递归过程来复制列表。
阅读评论以更好地理解操作过程中的“流程”。
- (defun copy-tree (x)
- ;; Return an exact copy of a given list.
- ;; (nested lists are this procedures speciality.)
- ;;
- ;; EX: (copy-tree '(1 2 (3 (4 5) 6 (nil)) 7 (()))
- ;; > (1 2 (3 (4 5) 6 (nil)) 7 (())
- (if (atom x) ; If "x" is only an item, not a list,
- x ; return the item...else,
- (cons (copy-tree (car x)) ; build a list, sending the next item
- ; back thru itself along with
- (copy-tree (cdr x)) ; the remander of the items,
- ; via backtrace.
- ;
- ; NOTE:
- ; last fuction `cons' returns assembled
- ; list of items or exact copy of what
- ; was passed to this procedure.
- )
- )
- )
利用上面的内容,我们可以构建一个稍微修改的版本来证明该列表中的数字。
|