获取Lisp中带有特殊编号的列表

时间:2016-04-03 22:18:38

标签: 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))
        )
    )
)

2 个答案:

答案 0 :(得分:2)

这是一个简单的方法:

(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)))

等...

答案 1 :(得分:0)

我用这种方式解决了我的问题:

(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))
        )
    )
)
相关问题