LISP编程-很想知道代码的功能
想知道上面的代码是做什么的吗?它定义了一个交错两个列表的函数。 例如,按如下方式调用:LISP编程-很想知道代码的功能,lisp,elisp,clisp,Lisp,Elisp,Clisp,想知道上面的代码是做什么的吗?它定义了一个交错两个列表的函数。 例如,按如下方式调用: (defun interleave (x y) (cond ((and (null x)(null y)) nil) (t (cons (car x) (cons (car y) (interleave (cdr x) (cdr y))))) 将给出列表(a d b e c f) 编辑 解释如下: (defun interleave(x y)声明接受2个参数(或列表)的函数interl
(defun interleave (x y)
(cond ((and (null x)(null y)) nil)
(t (cons (car x) (cons (car y) (interleave (cdr x) (cdr y)))))
将给出列表(a d b e c f)
编辑
解释如下:
声明接受2个参数(或列表)的函数(defun interleave(x y)
interleave
告诉我们,如果(cond((和(空x)(空y)nil)…)
和x
都是y
,则返回nil
nil
是空列表,函数nil
检查列表是否为空。在这里,该条件作为null
函数递归调用的终止交错
如果不满足上述条件,请指定默认操作(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
函数interleave
(interleave'(abc)'(def))
,递归可以表示为
(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)
角落案例也很有趣,比如输入(abc)和(01),那么条件2在做什么。你能解释一下(t(cons(car x)(cons(car y)(interleave(cdr x)(cdr yее)))吗?在答案中添加了一些解释:)谢谢你的解释
(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)