0

我正在尝试编写一个函数,该函数接受输入对列表和一个元素,该函数将返回包含该元素的所有对

这是我的代码:

(define find-node
  (lambda (x a-list)
    (if (null? a-list)
        "list null"
        (if (memq x (car a-list))
            (list (car a-list))
            (find-node x (cdr a-list))))))

这是我的输入,例如:'((dba) (ecb) (ec) (d) (be) (gf) (g))

预期输出:运行时(find-node 'b '((d b a) (e c b) (e c) (d) (b e) (g f) (g))),输出为 (dba) (ecb) (be)

上面代码的实际输出:(dba),这意味着这段代码只运行了 1 次......

请告诉我我错在哪里,我对递归不太熟悉......

4

1 回答 1

1

当找到一个元素时,您没有构建输出列表并推进递归。尝试这个:

(define find-node
  (lambda (x a-list)
    (if (null? a-list)
        '()                         ; when input is consumed, return empty list
        (if (member x (car a-list)) ; better use member
            (cons (car a-list)      ; here was the problem
                  (find-node x (cdr a-list))) ; advance the recursion
            (find-node x (cdr a-list))))))

现在它按预期工作:

(find-node 'b '((d b a) (e c b) (e c) (d) (b e) (g f) (g)))
=> '((d b a) (e c b) (b e))
于 2013-11-07T23:13:07.690 回答