;; 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 lect08-dist) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ; Data definition: ; A Book is: ; (make-book [string] [string] [int] [boolean]) (define-struct book (title author pages copyrighted?)) #| ; `define-struct` is like Java `class { ...}` but with only fields. class Book { String title; String author; int pages; boolean isCopyrighted; } |# ; Note that in Java, calling a constructor is not *quite* like ; calling most functions: ; it uses keyword `new`. ; new Book( "Goosebumps", "Stine", 37, true ) ; ((new Book( "Goosebumps", "Stine", 37, true )).toString()).length() ; (new Book("Goosebumps", "Stine", 37, true)).author (define scary (make-book "Goosebumps" "Stine" 37 true)) (make-book "Moby Dick" "Melville" 972 false) (book-title (make-book "Moby Dick" "Melville" 972 false)) ; getters ; (corresponding to Java .author, .title, .pages, .isCopyrighted) ; book-title : book -> string ; book-author : book -> string ; book-pages: book -> int ; book-copyrighted? : book -> boolean ; predicate: ; book? : ANY -> boolean ; WHEN YOU USE define-struct, ; RACKET DEFINES THE CONSTRUCTOR, GETTERS (ACCESSORS), and ; A PREDICATE FUNCTION FOR YOU. ; They're regular functions (no special syntax to call them). ;;;;;;;;;;;; (define-struct dvd (title runtime rating)) ; A DVD is: ; (make-dvd [string] [number] [symbol]) ; ; the constructor: ; make-dvd ; getters: ; dvd-title ; dvd-runtime ; dvd-rating ; Examples of the data: (make-dvd "Once" 100 'PG-13) (define fave (make-dvd "Once" 100 'PG-13)) (dvd-runtime fave) (check-expect (should-watch? fave) true) (check-expect (should-watch? (make-dvd "9" 182 'R)) true) (check-expect (should-watch? (make-dvd "Schindler's List" 182 'PG-13)) false) (check-expect (should-watch? (make-dvd "Scream" 85 'R)) true) ; should-watch? : dvd -> boolean (define (should-watch? some-dvd) (or (< (dvd-runtime some-dvd) 110) (symbol=? (dvd-rating some-dvd) 'R))) ; TEMPLATE for any function handling a dvd: ; func-for-dvd : dvd -> boolean ; (define (func-for-dvd a-dvd) ...(dvd-runtime a-dvd) ...(dvd-rating some-dvd) ...(dvd-title a-dvd))