我是 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/