Reputation: 1147
I'm trying to find a way to assign a list to a local variable, and then add that list to a symbol to make a new list, an improper list. Example below is to illustrate this:
Input: '?e1 ((?e1 ?e0) (?e1 ?ex) (?e1 ?ey) (?e1 ?e2))
Expected output: (?e1 (?e0 ?ex ?ey ?e2))
The idea is that compare (car graph) in all nested list with ?e1, add them together to form a list, assign the list to a variable, finally (list '?e1 (new list))
But actually the recursion make my code fail .....
I have try to write a program, but the output from this is quite ridiculous:
(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)
output is: '(?e1 ((?e0) ?e1 ((?ex) ?e1 ((?ey) ?e1 ((?e2))))))
Can someone please explain where I get wrong??? Thank you very much!!
Upvotes: 0
Views: 754
Reputation: 18917
You might want to get more acquainted with the fundamental Scheme procedures, since your procedure could simply be expressed as follows:
(define (find-dst node graph)
(cons node
(list
(map cadr
(filter (lambda (e) (eq? node (car e))) graph)))))
I would rewrite your example as follows:
(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))
EDIT
Regarding the additional question in your comment, if I understood it correctly, you could do something which is close:
(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 ()))
Upvotes: 1