;; 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_w_full) (read-case-sensitive #t) (teachpacks ((lib "image.ss" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "image.ss" "teachpack" "2htdp"))))) ; A ; / \ ; B C ; |\ / | ; D E F ; \ | / ; G ; arrows going down ; a graph is : ; (make-graph list-of-symbols (symbol -> list-of-symbols)) (define-struct graph (nodes neighbor)) (define mygraph (make-graph '(a b c d e f g) (lambda (node) (cond [(symbol=? node 'a) '(b c)] [(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-symbols or false) ; Returns a path in graph from origin to destination or false otherwise (define (find-path graph origin dest) (cond [(symbol=? origin dest) (list dest)] [else (maybe-cons origin (find-path/list graph ((graph-neighbor graph) origin) dest))])) (check-expect (find-path mygraph 'a 'd) (list 'a 'b 'd)) (check-expect (find-path mygraph 'd 'c) false) ; maybe-cons : symbol (list-of-symbol or false) -> (list-of-symbol or false) ; constructs a list if b is list, returns false otherwise (define (maybe-cons a b) (cond [(boolean? b) b] [else (cons a b)])) (check-expect (maybe-cons 'a (list 'b)) (list 'a 'b)) (check-expect (maybe-cons 'a false) false) ; find-path/list : graph list-of-symbols symbol -> (list-of-symbols or false) ; returns a path from one of origins to dest, or false if none (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))] )) (check-expect (find-path/list mygraph (list 'a 'g) 'd) (list 'a 'b 'd)) (check-expect (find-path/list mygraph (list 'g) 'd) false) ; pick-one : (list-of-symbols or false) (list-of-symbols or false) ; -> (list-of-symbols or false) ; returns list of symbols if one given, false otherwise (define (pick-one a b) (cond [(boolean? a) b] [else a]))