1

这是来自 HtDP 的练习 28.1.2。我已经成功实现了这个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]))]))

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

4

1 回答 1

1

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

于 2011-01-13T06:07:45.080 回答