;; 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-reader.ss" "lang")((modname struct-intro-after) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; a book has info: ;; title, author, # of pages, is copyrighted? ; Data Definiton: ; A book is: ; (make-book [string] [string] [natnum] [boolean]) (define-struct book (title author num-pages is-copyrighted?)) ; Examples of the data (define b1 (make-book "The Cat in the Hat" "Seuss" 37 #true)) (define b0 (make-book "The Soul of Wit" "Barland" 0 #false)) ; `define-struct` actually introduces additional functions: ; a constructor ; and four getters ("selectors"). ; In this case, the constructor is named ; make-book : string, string, natural, boolean -> book ; and the getters are named ; book-title : book -> string ; book-author : book -> string ; book-num-pages ; book-is-copyrighted? (book-title (make-book "The Cat in the Hat" "Seuss" 37 #true)) (book-is-copyrighted? b0) ;;;;;;;;;;;;;;;;;;; ; Template for any book-processing function: (define (func-for-book a-book) (... (book-title a-book) ... (book-author a-book) ... (book-num-pages a-book) ... (book-is-copyrighted? a-book) )) ; reading-time : book -> non-negative real ; The amount of time it takes the average reader to read a book (in minutes) ; (define (reading-time a-book) (* 2 (book-num-pages a-book))) (check-expect (reading-time (make-book "The Cat in the Hat" "Seuss" 37 #true)) 74) (check-expect (reading-time b0) 0) ; book->string : book -> string ; Return a string-representation of a book struct, user-friendly. (define (book->string a-book) (string-append (book-title a-book) ", by " (book-author a-book) " (" (number->string (book-num-pages a-book)) "pp)" (if (book-is-copyrighted? a-book) ", ©" ""))) (check-expect (book->string (make-book "The Cat in the Hat" "Seuss" 37 #true)) "The Cat in the Hat, by Seuss (37pp), ©") (check-expect (book->string b0) "The Soul of Wit, by Barland (0pp)") ; derive-from : book, string, natnum -> book ; Create a brand new book, based on an original. ; The result's author will be the original author & the new-author, ; and the result has pages added to the original. ; (define (derive-from a-book new-author added-pages) (make-book (string-append "Son of " (book-title a-book)) (string-append (book-author a-book) " & " new-author) (+ (book-num-pages a-book) added-pages) #false)) (check-expect (derive-from b1 "Sauced" 3) (make-book "Son of The Cat in the Hat" "Seuss & Sauced" 40 #false)) (check-expect (derive-from b0 "Freund" 0) (make-book "Son of The Soul of Wit" "Barland & Freund" 0 #false))