Scheme Find all possible paths for an undirected g

2019-07-31 06:50发布

I am having problem to print out all the possible paths. Currently I am only able to print out one path, and if (path-demo "J" "I"), the program will shown this error mcdr: expects argument of type <mutable-pair>; given #f

 (define net
  '(("A" "B")
    ("B" "A" "C")
    ("C" "B" "D")
    ("D" "C" "E" "F")
    ("F" "I" "D")
    ("I" "F")
    ("E" "D" "J")
    ("J" "E" "G")
    ("G" "J" "H"))) 

 (define (path-demo start finish)
         (for-each (lambda (x) (display x) (display " "))
                   (cons "Route:" (shortest-path start finish net))))

 (define (shortest-path start end net)
    (bfs end (list (list start)) net))

 ;; Breadth-first search
  (define (bfs end queue net)
    (display queue) (newline) (newline) ; entertainment
    (if (null? queue)
      '()
      (let ((path (car queue)))
       (let ((node (car path)))
         (if (equal? node end) ;; Graham used CL eql
             (reverse path)
             (bfs end 
                  (append (cdr queue)
                          (new-paths path node net))
                  net))))))

 (define (new-paths path node net)
   (map (lambda (n) (cons n path)) (cdr (assoc node net))))

;;
(path-demo "J" "I")

2条回答
Anthone
2楼-- · 2019-07-31 07:19

It is likely that the following returns #f:

(cdr (assoc node net))

Regarding comment (for formatting):

(define (new-paths path node net)
   (write node)
   (newline)
   (map (lambda (n) (cons n path)) (cdr (assoc node net))))
查看更多
The star\"
3楼-- · 2019-07-31 07:23

In your definition of net you have forgotten to list the nodes to which H is connected.

When the error occurs node and net have the following values:

node: H 
net: ((A B) (B A C) (C B D) (D C E F) (F I D) (I F) (E D J) 
      (J E G) (G J H)))

Thus

(assoc node net))

will return #f because H has no associations in net. And this leads to the error from cdr:

cdr: expects argument of type <pair>; given #f
查看更多
登录 后发表回答