【发布时间】:2020-04-18 19:25:53
【问题描述】:
(defun interleave (x y)
(cond ((and (null x)(null y)) nil)
(t (cons (car x) (cons (car y) (interleave (cdr x) (cdr y)))))
很想知道上面的代码是做什么的?
【问题讨论】:
(defun interleave (x y)
(cond ((and (null x)(null y)) nil)
(t (cons (car x) (cons (car y) (interleave (cdr x) (cdr y)))))
很想知道上面的代码是做什么的?
【问题讨论】:
它定义了一个交错两个列表的函数。 例如,如下调用:
(interleave '(a b c) '(d e f))
将给出列表(a d b e c f)。
编辑
解释如下:
(defun interleave (x y) .. 声明函数 interleave 接受 2 个参数(或列表)(cond ((and (null x)(null y) nil) ...) 告诉如果 both x 和 y 都是 nil,则返回 nil。 nil 是空列表,函数 null 检查列表是否为空。在这里,条件作为 interleave 函数递归调用的终止。(t ...)指定不满足以上条件的默认动作(cons ...) 通过指定列表的头部(第一个参数)和尾部(第二个参数)来构造一个新列表。例如:(cons a '(b c)) 将给出(a b c)。请注意,头部应该是单个元素,尾部应该是元素列表。 cons 的一个有用属性是:(cons a nil) => (a)。(car x) 检索列表的头部x。例如:(car '(a b c)) 将返回 a。 car 的一个有用属性是:(car nil) => nil。(cdr x) 检索列表的尾部 x。例如:(cdr '(a b c)) 将返回 (b c)。 cdr 的有用属性是:
nil:(cdr (a)) => nil nil 的尾部是nil:(cdr nil) => nil。(interleave (cdr x) (cdr y)) 以x 和y 的tail 作为参数递归调用interleave 函数。所以,对于(interleave '(a b c) '(d e f))的调用,递归可以表示如下
(interleave '(a b c) '(d e f))
(cons a (cons d (interleave (b c) (e f)))
(cons a (cons d (cons b (cons e (interleave (c) (f))))))
(cons a (cons d (cons b (cons e (cons c (cons f (interleave nil nil)))))))
(cons a (cons d (cons b (cons e (cons c (cons f nil))))))
(cons a (cons d (cons b (cons e (cons c (f))))))
(cons a (cons d (cons b (cons e (c f)))))
(cons a (cons d (cons b (e c f))))
(cons a (cons d (b e c f)))
(cons a (d b e c f))
(a d b e c f)
对于两个列表长度不相等的情况,我们有例子:
(interleave '(a b c) '(1 0))
(cons a (cons 1 (interleave (b c) (0))))
(cons a (cons 1 (cons b (cons 0 interleave (c) nil))))
(cons a (cons 1 (cons b (cons 0 (cons c (cons nil (interleave nil nil)))))))
(cons a (cons 1 (cons b (cons 0 (cons c (cons nil nil))))))
(cons a (cons 1 (cons b (cons 0 (cons c (nil))))))
(cons a (cons 1 (cons b (cons 0 (c nil)))))
(cons a (cons 1 (cons b (0 c nil))))
(cons a (cons 1 (b 0 c nil)))
(cons a (1 b 0 c nil))
(a 1 b 0 c nil)
【讨论】: