list - 在 Lisp 中获取具有特殊编号的列表

标签 list lisp

我是 Lisp 的新手,我需要创建函数来返回包含特殊数字的子列表的第二个值。

例如,我有一个带有两个参数的函数:其中一个是带有子列表的列表,第二个是我要搜索的特殊数字:

 (find_neighbours '((1 2) (3 1) (4 5) (9 1) (2 3) (1 5)) 1)

那个函数应该返回类似的东西:

(2 3 9 5)

因为我们在 (1 2) (3 1) ... 中有带 1 的子列表。

这是我的解决方案:

(defun find_neighbours (lst node)
    (if lst
        (cond 
            ((= node (caar lst))  
                (cons (cadar lst) 
                (find_neighbours (cdr lst) node))
            )
            ((= node (cadar lst)) 
                (cons (caar  lst) 
                (find_neighbours (cdr lst) node))
            )
            (T (find_neighbours (cdr lst) node))
        )
    )
)

最佳答案

这里有一个简单的方法:

(defun other-end (edge vertex)
  "Return the other end of the EDGE if VERTEX is one of them or NIL."
  (destructuring-bind (beg end) edge
    (cond ((= vertex beg) end)
          ((= vertex end) beg)
          (t nil))))

(defun neighbors (graph vertex)
  "Return the list of neighbors of the VERTEX in the GRAPH."
  (loop for edge in edges
    for other = (other-end edge vertex)
    when other collect other))

还有其他方法,例如,

(defun neighbors (graph vertex)
  "Return the list of neighbors of the VERTEX in the GRAPH."
  (delete nil (mapcar (lambda (edge) (other-end edge vertex))
                      graph)))

等...

关于list - 在 Lisp 中获取具有特殊编号的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36391932/

相关文章:

macros - 让出 Lambda : symbolic representation in macros

python - 属性错误 : 'NoneType' object has no attribute 'append' (recursion function)

list - 将列表转换为 data.map 给出类型错误

python - 如何从两个列表中查找匹配项(来自 MySQL 和 csv)

c# - 如何刷新 Windows Phone 中的列表框

LISP 嵌套循环并行执行。如何强制它按顺序执行?

python - 如何将列表转换为使用元组作为键的字典

lisp中的搜索功能

scope - 为什么这个函数每次都返回不同的值?

list - cond with 列表中的 Scheme