#| ----------------------------------------------------------------- A bookstore manager wishes to manage her inventory using a computer program. Some of the things she'd like to do: - find out how many copies there are of a specific title - determine the total value of the inventory - update the inventory to reflect sales or restocking - sort the inventory in descending order of inventory value - ... ------------------------------------------------------------------ |# (define-struct book (title price quantity)) ;; A Book is (make-book String Number Number) ;; A LoB (short for list of books) is one of ;; - empty ;; - (cons Book LoB) #| Template ;; f : LoB -> ??? (define (f alob) (cond [(empty? alob) ... ] [(cons? alob) ... (book-title (first alob)) ... ... (book-price (first alob)) ... ... (book-quantity (first alob)) ... ... (f (rest alob)) ... ])) |# ;; how-many : LoB String -> Number ;; count how many of title are in alob (define (how-many alob title) (cond [(empty? alob) 0] [(cons? alob) (cond [(string=? (book-title (first alob)) title) (book-quantity (first alob))] [else (how-many (rest alob) title)])])) ;; total : LoB -> Number ;; compute total value of inventory (define (total alob) (cond [(empty? alob) 0] [(cons? alob) (+ (* (book-price (first alob)) (book-quantity (first alob))) (total (rest alob)))])) ;; update : LoB String Number -> LoB ;; to update the inventory (define (update alob title change) (cond [(empty? alob) (cons (make-book title 0 change) empty)] [(cons? alob) (cond [(string=? (book-title (first alob)) title) (cons (update-book (first alob) change) (rest alob))] [else (cons (first alob) (update (rest alob) title change))])])) ;; update-book : Book Number -> Book ;; updates the quantity of the given book (define (update-book a-book change) (make-book (book-title a-book) (book-price a-book) (+ change (book-quantity a-book)))) ;; Book examples (define book1 (make-book "Hobbit" 35.99 50)) (define book2 (make-book "Cat in the Hat" 10.00 20)) (define book3 (make-book "HtDP" 69.95 1000)) ;; LoB examples (define lob1 empty) (define lob2 (cons book1 empty)) (define lob3 (cons book1 (cons book2 (cons book3 empty)))) ;; Examples/tests for how-many (equal? (how-many lob1 "HtDP") 0) (equal? (how-many lob3 "Hobbit") 50) (equal? (how-many lob3 "Cat in the Hat") 20) ;; Examples/tests for total (equal? (total lob1) 0) (equal? (total lob2) (* 35.99 50)) ;; Examples/tests for update-book (equal? (update-book book1 20) (make-book "Hobbit" 35.99 70)) (equal? (update-book book1 -10) (make-book "Hobbit" 35.99 40)) ;; Examples/tests for update (equal? (update lob1 "TLL" 7) (cons (make-book "TLL" 0 7) empty)) (equal? (update lob3 "Cat in the Hat" -10) (cons book1 (cons (make-book "Cat in the Hat" 10.00 10) (cons book3 empty))))