我正在尝试找到一种方法将列表分配给局部变量,然后将该列表添加到符号中以创建新列表,这是一个不正确的列表。以下示例说明了这一点:
输入:'?e1 ((?e1 ?e0) (?e1 ?ex) (?e1 ?ey) (?e1 ?e2))
预期输出:(?e1 (?e0 ?ex ?ey ?e2))
想法是将所有嵌套列表中的(车图)与?e1进行比较,将它们一起添加以形成列表,将列表分配给变量,最后(列出'?e1(新列表))
但实际上递归使我的代码失败.....
我试着写一个程序,但是这个输出非常荒谬:
(define agrv '((?e1 ?e0) (?e1 ?ex) (?e1 ?ey) (?e1 ?e2)))
(define successor
(lambda (node graph)
(if (equal? node (car graph))
(cdr graph)
'())))
(define (find-dst node graph)
(if (null? graph)
'()
(let ((custom-list (append (list (successor node (car graph))) (find-dst node (cdr graph)))))
(list node custom-list))))
(find-dst '?e1 agrv)
输出为:'(?e1 ((?e0) ?e1 ((?ex) ?e1 ((?ey) ?e1 ((?e2))))))
有人可以解释我哪里出错了???非常感谢!!
答案 0 :(得分:1)
您可能希望更熟悉基本的Scheme程序,因为您的程序可以简单地表达如下:
(define (find-dst node graph)
(cons node
(list
(map cadr
(filter (lambda (e) (eq? node (car e))) graph)))))
我会按如下方式重写你的例子:
(define (find-dst node graph)
(define (sub graph)
(if (null? graph)
null
(let ((e (car graph)))
(if (eq? node (car e))
(cons (cadr e) (sub (cdr graph)))
(sub (cdr graph))))))
(cons node (list (sub graph))))
(find-dst '?e1 '((?e1 ?e0) (?e1 ?ex) (?e1 ?ey) (?e1 ?e2)))
=> '(?e1 (?e0 ?ex ?ey ?e2))
修改强>
关于评论中的其他问题,如果我理解正确,你可以做一些接近的事情:
(define (find-dst2 node graph)
(let ((r (find-dst node graph)))
(cons node
(map (lambda (e) (find-dst e graph)) (cadr r)))))
(find-dst2 '?e1 '((?e1 ?e0) (?e0 ?ex) (?e0 ?ey) (?e1 ?e2)))
=> '(?e1 (?e0 (?ex ?ey)) (?e2 ()))