【问题标题】:LISP programming - Curious to know what that code doesLISP 编程 - 很想知道该代码的作用
【发布时间】: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)))))

很想知道上面的代码是做什么的?

【问题讨论】:

    标签: lisp elisp clisp


    【解决方案1】:

    它定义了一个交错两个列表的函数。 例如,如下调用:

    (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 xy 都是 nil,则返回 nilnil 是空列表,函数 null 检查列表是否为空。在这里,条件作为 interleave 函数递归调用的终止。
    • (t ...)指定不满足以上条件的默认动作
    • (cons ...) 通过指定列表的头部(第一个参数)和尾部(第二个参数)来构造一个新列表。例如:(cons a '(b c)) 将给出(a b c)。请注意,头部应该是单个元素,尾部应该是元素列表。 cons 的一个有用属性是:(cons a nil) => (a)
    • (car x) 检索列表的头部x。例如:(car '(a b c)) 将返回 acar 的一个有用属性是:(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))xytail 作为参数递归调用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)
    

    【讨论】:

    • 极端情况也很有趣,例如输入 (a b c) 和 (0 1)
    • 那么条件2在做什么。你能解释一下 (t (cons (car x) (cons (car y) (interleave (cdr x) (cdr y))))) 吗?
    • 在答案中添加了一些解释:)
    • 感谢您的解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多