我有一个方法,我想在其中创建一个空列表,在其中附加一些值,然后返回该列表。我的方法不断返回一个空列表。我做错了什么?
(define-struct graph (vertices edges))
(define-struct vertice (name visited))
(define-struct edge (start-vertice end-vertice length))
;I create data for testing here
(define vertices-list2
(list (make-vertice 0 0)
(make-vertice 1 0)
(make-vertice 2 0)
)
)
(define edges-list2
(list (make-edge 0 1 0)
(make-edge 1 2 0)
)
)
(define (find-adj V edge-list)
(let ((ret '()))
(cond
[(empty? edge-list) ret]
[(eq? V (edge-start-vertice (car edge-list)))
(begin
(append ret '((edge-end-vertice (car edge-list))) )
(find-adj V (cdr edge-list)))
]
[else (find-adj V (cdr edge-list))]
)
)
)
(define G (make-graph vertices-list2 edges-list2))
(find-adj 0 (graph-edges G))
答案 0 :(得分:2)
您的代码中存在多个错误。我有一些建议:
begin
内cond
,这是隐含的。equal?
代替eq?
,因为它是一种更为一般的比较程序。append
返回的值作为参数传递,否则您将执行空操作。edge-end-vertice
,您只需附加一个符号列表,而不是因为开头的引号而调用过程。ret
变量,否则您将在每次调用时覆盖结果。请记住,append
和所有其他列表操作不会就地修改列表,它们只会返回一个新列表 - 如果您不保存它或将其作为参数传递(在这种情况下,这将是首选),您将失去修改。如果你将ret
作为参数传递它会更好,所以它的值保持在调用之间 - 我们可以为它定义一个帮助程序:
(define (find-adj V edge-list)
(define (helper edge-list ret)
(cond
[(empty? edge-list) ret]
[(equal? V (edge-start-vertice (car edge-list)))
(helper (cdr edge-list)
(append ret (edge-end-vertice (car edge-list))))]
[else (helper (cdr edge-list) ret)]))
(helper edge-list '()))