RU beehive logo ITEC dept promo banner
ITEC 380
2009fall
ibarland

homeinfolecturesexamshwsarchive

lect03c
design recipe; functions returning structs

We saw last time:

;A book is:
;   (make-book [string] [string] [number] [boolean])
;
(define-struct book (title author pages copyR?))

; Examples of the data:
(make-book "The Soul of Wit" "Shorty" 0 false)
(define b1 (make-book "The Cat in the Hat" "Seuss" 31 true))


; Note that 'define-struct' automagically creates
; functions for us:
; Constructor:
;   make-book: string, string, number, boolean -> book
; Selectors:
;   book-title  : book -> string
;   book-author : book -> string
;   book-pages  : book -> number
;   book-copyR? : book -> boolean


; read-time: book -> number
; How long does it take to read the book, in hours?
;




(check-expect (read-time (make-book "The Soul of Wit" "Shorty" 0 false)) 0)
(check-expect (read-time b1) (+ 1 2/60))
After making the test cases, we go back and write the code:
; read-time: book -> number
; How long does it take to read the book, in hours?
;
(define (read-time a-book)
  (* (book-pages a-book) 2 1/60))
(We also saw Java analogs of all this.)

The Design Recipe

(Adapted from How to Design Programs)
For each type of data involved:
    1. Data Definition (how will you represent an age, a gender, a book, etc.)
    2. Examples of the Data   (trivial first)
Then, for each function involving that data:
    3. description, signature, and header/stub
    4. test cases
    5a. selectors  (what is the type of each?)
    5b. add any natural/pertinent function calls on these pieces
    5c. assemble the parts of 5b.  
    6. Run tests.

Practice: book->String.

Practice: derive-from.

Btw: How to go back and improve our existing function read-time? Use named constants. (Two of 'em.)

homeinfolecturesexamshwsarchive


©2009, Ian Barland, Radford University
Last modified 2009.Sep.11 (Fri)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme