回溯无限循环

时间:2011-01-13 04:47:36

标签: scheme racket

这是Exercise 28.1.2 from HtDP。我已经成功实现了neighbors函数,所有测试用例都通过了。

(define Graph (list
               (list 'A (list 'B 'E))
               (list 'B (list 'E 'F))
               (list 'C (list 'D))
               (list 'D empty)
               (list 'E (list 'C 'F))
               (list 'F (list 'D 'G))
               (list 'G empty)))

(define (first-line n alist)
  (cond
    [(symbol=? (first alist) n) alist]
    [else empty]))

;; returns empty if node is not in graph
(define (neighbors n g)
  (cond
    [(empty? g) empty]
    [(cons? (first g)) 
     (cond
       [(symbol=? (first (first g)) n) (first-line n (first g))]
       [else (neighbors n (rest g))])]))

; test cases
(equal? (neighbors 'A Graph) (list 'A (list 'B 'E)))
(equal? (neighbors 'B Graph) (list 'B (list 'E 'F)))
(equal? (neighbors 'C Graph) (list 'C (list 'D)))
(equal? (neighbors 'D Graph) (list 'D empty))
(equal? (neighbors 'E Graph) (list 'E (list 'C 'F)))
(equal? (neighbors 'F Graph) (list 'F (list 'D 'G)))
(equal? (neighbors 'G Graph) (list 'G empty))
(equal? (neighbors 'H Graph) empty)

当我从文本的Figure 77复制粘贴代码时出现问题。它应该确定目标节点是否可以从原始节点到达。然而,似乎代码进入无限循环,除了原始节点和目标节点相同的最简单的情况。

;; find-route : node node graph  ->  (listof node) or false
;; to create a path from origination to destination in G
;; if there is no path, the function produces false
(define (find-route origination destination G)
  (cond
    [(symbol=? origination destination) (list destination)]
    [else (local ((define possible-route 
            (find-route/list (neighbors origination G) destination G)))
        (cond
          [(boolean? possible-route) false]
          [else (cons origination possible-route)]))]))

;; find-route/list : (listof node) node graph  ->  (listof node) or false
;; to create a path from some node on lo-Os to D
;; if there is no path, the function produces false
(define (find-route/list lo-Os D G)
  (cond
    [(empty? lo-Os) false]
    [else (local ((define possible-route (find-route (first lo-Os) D G)))
        (cond
          [(boolean? possible-route) (find-route/list (rest lo-Os) D G)]
          [else possible-route]))]))

问题出在我的代码中吗?谢谢。

1 个答案:

答案 0 :(得分:1)

好的问题确实存在于我自己的代码中。我应该返回一个列表,而不是包含节点及其相邻节点的列表。即(neighbor 'A Graph)应该生成(list 'B 'E),而不是(list 'A (list 'B 'E))