【问题标题】:LISP compare an Element in a BoardLISP 比较板上的元素
【发布时间】:2014-12-13 00:44:11
【问题描述】:

我正在用 Common Lisp 为大学做一个项目

我需要比较一个 4x4 列表 示例:

(
((white full circle) (black empty circle) (black full circle) (white empty circle))
(0 0 0 0)
(0 0 0 0)
(0 0 0 0)
)

我需要比较一行是否有 4 个共享一个元素的列表,在本例中为“圆圈” 而且我不能使用任何defvar之类的交集,需要递归地使用它,而且我找不到方法来做到这一点

【问题讨论】:

    标签: list recursion lisp common-lisp


    【解决方案1】:

    试试这个:

    (defun find-common (x)
      (labels ((compare (items lst)
                (cond ((null items) nil)
                  ((not (remove-if #'(lambda (k) (member (car items) k)) lst))
                   (cons (car items) (compare (cdr items) lst)))
                  (t (compare (cdr items) lst)))))
        (cond ((null x) nil)
          (t (cons (compare (caar x) (car x)) 
                   (find-common (cdr x)))))))
    

    要查看列表列表是否共享一个公共元素,我们必须检查该列表的car 中的每个元素是否也出现在其cdr 的每个列表中。这就是compare 函数的作用。它递归地检查一个元素是否出现在所有列表中。

    find-common 函数递归搜索列表列表中所有常见的事件。

    假设table 是您的 4 x 4 列表:

    (setf table
        '(((white full circle) (black empty circle) (black full circle) (white empty circle))
          ((3 2 8 5) (2 9 1 8) (23 8 2 1) (3 8 0 2))
          ((one five six) (six one five) (five one six) (one six five))
          ((green blue red) (green red blue) (silver red white) (green yellow blue))))
    

    调用find-common函数:

    >(find-common table)
    
    ((CIRCLE) (2 8) (ONE FIVE SIX) NIL)
    

    【讨论】:

    • 不要在函数体中使用defun。它不会做你认为它会做的事情。它将定义一个顶级函数。使用fletlabels 定义本地函数。另外,请使用正确的缩进和代码格式。
    • @Svante,谢谢。相应地编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多