在 Lisp 中获取具有特殊编号的列表
Get list with special number in Lisp
我是 Lisp 的新手,我需要制作比 return 包含特殊数字的子列表的第二个值更重要的功能。
例如,我有两个参数的函数:其中一个是带有子列表的列表,第二个是我要搜索的特殊号码:
(find_neighbours '((1 2) (3 1) (4 5) (9 1) (2 3) (1 5)) 1)
那个函数应该return类似这样的东西:
(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)))
等...
我这样解决了我的问题:
(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))
)
)
)
我是 Lisp 的新手,我需要制作比 return 包含特殊数字的子列表的第二个值更重要的功能。
例如,我有两个参数的函数:其中一个是带有子列表的列表,第二个是我要搜索的特殊号码:
(find_neighbours '((1 2) (3 1) (4 5) (9 1) (2 3) (1 5)) 1)
那个函数应该return类似这样的东西:
(2 3 9 5)
因为我们在 (1 2) (3 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)))
等...
我这样解决了我的问题:
(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))
)
)
)