我正在尝试编写一个函数,它接受输入对和列表的元素,该函数将返回包含元素的所有对
这是我的代码:
(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))))))
这是我的意见,例如:'((d b a)(e c b)(e c)(d)(b e)(g f)(g))
预期输出:当运行(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)
上面代码的实际输出:(d b a),这意味着此代码只运行1次....
请告诉我我哪里错了,我对递归并不熟悉....
答案 0 :(得分: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))