首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查Cons列表中是否存在Cons

检查Cons列表中是否存在Cons
EN

Stack Overflow用户
提问于 2021-11-15 21:15:31
回答 1查看 30关注 0票数 0

我正在构建一个程序和lisp,需要检查cons是否存在于Cons列表中,但由于某种原因,它在if语句中总是返回nil,以下是我正在使用的当前代码。

代码语言:javascript
复制
(defun countVertexTriangles (graph numOfVertices)
    (findTriangle graph numOfVertices)
)

(defun findTriangle(graph numOfVertices)
    (loop for (x y) in graph do
            (loop for z from 1 to numOfVertices do
                (write graph)
                (terpri)
                (write (cons z (cons y nil)))
                (terpri)
                (write (cons z (cons x nil)))
                (terpri)
                ; (if (AND (member (cons z (cons y nil)) graph) (member (cons z (cons x nil)) graph))
                ;     then (write (cons y z))
                ; )
            )
        (terpri)
    )
)

; (defun findEdge(graph edge)
;     (loop for x in graph do
;         (write x)
;         (write edge)
;         (if (eql x edge)
;             (write "A")
;             (write "B")
;         )
;     )
; )

(defun testFunct ()
    (setf g1 '((1 2)(2 3)(1 3)(2 4)(3 4)(4 5)(3 5)))
    (countVertexTriangles g1 5)
)

(testFunct)

为什么成员(cons z(Cons Y nil))返回nil,即使在第一次迭代中我们可以看到(1,2)存在于列表中?

编辑:

目前,即使它是真的,它也会返回nil,为什么在给定以下代码时会出现这种情况?

代码语言:javascript
复制
(defun countVertexTriangles (graph numOfVertices)
    (findTriangle graph numOfVertices)
)

(defun findTriangle(graph numOfVertices)
    (loop for (x y) in graph do
            (loop for z from 1 to numOfVertices do
                ; (write graph)
                ; (terpri)
                ; (write (list z y ))
                ; (terpri)
                (write (findEdge graph (list z y)))
                (terpri)
                ; (if (AND (member (list z x) graph) (member (list z x ) graph))
                ;     then (write "TEST")
                ; )
            )
        (terpri)
    )
)

(defun findEdge(graph edge)
    (loop for x in graph do
        (if (equal x edge)
            (return-true)
            (return-false)
        )
    )
)

(defun return-true ()
   t)

(defun return-false ()
   nil)

(defun testFunct ()
    (setf g1 '((1 2)(2 3)(1 3)(2 4)(3 4)(4 5)(3 5)))
    (countVertexTriangles g1 5)
)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-15 21:57:32

findEdge不返回任何内容。调用return-truereturn-false不会从findEdge返回。在找到匹配项之前,您也不应该返回。

代码语言:javascript
复制
(defun findEdge(graph edge)
    (loop for x in graph do
        (if (equal x edge)
            (return-from findEdge (return-true))
        )
    )
    (return-false)
)

这可以简化为:

代码语言:javascript
复制
(defun findEdge (graph edge) 
  (member edge findEdge :test #'equal))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69980973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档