Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LISP编程-很想知道代码的功能_Lisp_Elisp_Clisp - Fatal编程技术网

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)

编辑

解释如下:

  • (defun interleave(x y)
    声明接受2个参数(或列表)的函数
    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)