;; 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-beginner-abbr-reader.ss" "lang")((modname 06two-lists-lockstep) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ;; DEMO: Working with two lists in lockstep #| DATA DESCRIPTION A *station* is a structure: > `(make-station name distance)` where `name` is a string and `distance` is a number of miles from Boston A *stop* is either - A station - A horde of zombies `(make-zombies distance)` |# (define-struct station (name distance)) (define-struct zombies (distance)) ;DATA EXAMPLES (define yalez (make-zombies 156)) (define brownz (make-zombies 40)) (define bos (make-station "South Station" 0)) (define bby (make-station "Back Bay" 1.1)) (define pvd (make-station "Providence" 42.6)) (define nhv (make-station "New Haven" 156.4)) (define nro (make-station "New Rochelle" 212.1)) (define nyp (make-station "NY Penn Station" 228.7)) (define stations (list nyp nro nhv pvd bby bos)) (define zs (list 0 0 7 83 40 0)) (check-expect (tally-invasion (list nyp bby) (list 0 40)) (list nyp (make-zombies 1.1))) (check-expect (tally-invasion empty empty) empty) ;; tally-invasion : list-of-stations list-of-natural-numbers -> list-of-stops ;; from the given stations and zombie populations, which must be the same ;; length, create a list of stops by ;; allowing a zombie horde to replace every station where zombie population ;; is nonzero (define (two-lists-template stns zs) (cond [(empty? stns) (cond [(empty? zs) ...] [(cons? zs) (... (first zs) ... (rest zs) ...)])] [(cons? stns) (cond [(empty? zs) (... (first stns) ... (rest stns) ...)] [(cons? zs) (... (first zs) ... (rest zs) ... (first stns) ... (rest stns) ...)])])) ;; **lockstep** template: 'both cons' or 'both empty' (define (lockstep-template stns zs) (cond [(and (empty? stns) (empty? zs)) ...] [(and (cons? stns) (cons? zs)) (... (first zs) ... (rest zs) ... (first stns) ... (rest stns) ...)])) ;; **lockstep** template: 'both cons' or 'both empty' (define (lockstep-template-with-natural-recursion stns zs) (cond [(and (empty? stns) (empty? zs)) ...] [(and (cons? stns) (cons? zs)) (... (first stns) ... (first zs) ... (lockstep-template-with-natural-recursion (rest stns) (rest zs)))])) ;; tally-invasion : list-of-stations list-of-natural-numbers -> list-of-stops ;; from the given stations and zombie populations, create a list of stops by ;; allowing a zombie horde to replace every station where zombie populatino ;; is nonzero (define (tally-invasion stns zs) (cond [(and (empty? stns) (empty? zs)) empty] [(and (cons? stns) (cons? zs)) (cons (station-or-horde (first stns) (first zs)) (tally-invasion (rest stns) (rest zs)))])) (define (station-or-horde stn z) (cond [(zero? z) stn] [(positive? z) (make-zombies (station-distance stn))]))