【问题标题】:Merge lists in Lisp在 Lisp 中合并列表
【发布时间】:2015-10-29 04:53:18
【问题描述】:

我正在尝试获取表示二叉搜索树的列表并按顺序输出列表元素,因此(displayBST '(10(5(3(2()())())())())) -> (2 3 5 10)。我似乎能得到的只是看起来像(((2 3) 5) 10) 的列表,我不确定如何使所有数字成为基本元素。

(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (first elements))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (list (displayBST(second elements)) (first elements))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (list (first elements) (displayBST(third elements))))))))

【问题讨论】:

  • 您可以在结果列表中使用flatten (((2 3) 5) 10)

标签: recursion lisp common-lisp


【解决方案1】:

考虑一下如何将给定元素连接到函数递归返回的值。如果你想要 X + Y = (X Y),你应该使用 (cons X (list Y))。因此基本情况(即(null(第二个元素))和(null(第三个元素))应该返回(list(第一个元素))。 你想要的是这样的:

(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (list (first elements)))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (append (displayBST(second elements)) (list (first elements)))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (cons (first elements) (displayBST(third elements))))))))

【讨论】:

  • 在词法闭包中定义一个(顶级)函数是有效的,但可能会产生有趣的(我所说的“有趣”,我可能是指“可怕”)的后果。最好将实现的适当较小部分包装在由函数内部的let 创建的词法环境中(酌情使用fletlabels)。
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多