;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-advanced-reader.ss" "lang")((modname week9_m) (read-case-sensitive #t) (teachpacks ((lib "image.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "image.ss" "teachpack" "htdp"))))) ; graphs ;; a graph is: ;; (make-graph (listof symbol) (symbol -> (listof symbol))) (define-struct graph (nodes neighbor)) ; A ; / ; / ; B C ; |\ /| ; | \/ | ; D E F ; \ | / ; \|/ ; G ; (arrows pointing down) (define mygraph (make-graph '(a b c d e f g) (lambda (node) (cond [(symbol=? node 'a) '(b)] [(symbol=? node 'b) '(d e)] [(symbol=? node 'c) '(e f)] [(member node '(d e f)) '(g)] [(symbol=? node 'g) '()])))) ; find-path : graph symbol symbol -> list-of-symbol or false ; returns path between origin and dest if exists, otherwise false (define (find-path g origin dest) (cond [(symbol=? origin dest) (list dest)] [else (maybe-cons origin (find-path/list g ((graph-neighbor g) origin) dest))])) (check-expect (find-path mygraph 'a 'd) (list 'a 'b 'd)) (check-expect (find-path mygraph 'a 'c) false) ;; maybe-cons : symbol (list-of-symbols or false) -> list-of-symbols or false ; returns false if second arg false, otherwise list with symbol pre-pended (define (maybe-cons a b) (cond [(boolean? b) b] [else (cons a b)])) ; find-path/list : graph list-of-symbol symbol -> list-of-symbol or false ; returns a path from any nodes in list to dest or false if none exists ; (cond [(empty? origins) ...] ; [else ... (first origins) .... (fun-for-list-of-symbols (rest origins))] (define (find-path/list graph origins dest) (cond [(empty? origins) false] [else (pick-one (find-path graph (first origins) dest) (find-path/list graph (rest origins) dest))]) ) ;pick-one : (list-of-symbol or false) (list-of-symbol or false) -> list-of-symbol or false (define (pick-one a b) (cond [(boolean? a) b] [else a] ))