;; Examples from Chapter 7 with added comments and tests ;; structure square represents a square shape ;; nw is posn that represents the coordinates of the north-west ;; (left-upper) corner of the square ;; length is a positive number that represents the length ;; of the side of the square (define-struct square (nw length)) ;; structure circle represents a circle shape ;; center is a posn that represents the coordinates ;; of the center of the circle ;; radius is a positive number that represents ;; its radius (define-struct circle (center radius)) (make-square (make-posn 20 20) 100) (make-circle (make-posn 50 100) 50) ;; a shape is either a square or a circle ;; pi is a built-in constant. It's an inexact number. pi ;; every structure comes with a function that checks for ;; the structure type. The name of the function is the ;; structure type followed by a question mark: (circle? (make-circle (make-posn 50 100) 50)) (square? (make-circle (make-posn 50 100) 50)) (posn? (make-posn 3 5)) (posn? 7) ;; perimeter: shape -> number ;; purpose: to compute perimeter of a shape (define (perimeter a-shape) (cond [(square? a-shape) (* (square-length a-shape) 4)] [(circle? a-shape) (* (* 2 (circle-radius a-shape)) pi)])) ;; a square with the side length of 100 has perimeter = 400: (check-expect (perimeter (make-square (make-posn 20 20) 100)) 400) ;; a circle of radius 50 has perimeter = pi * 100 ;; since this is an inexact number, we use check-within (check-within (perimeter (make-circle (make-posn 50 100) 50)) (* pi 100) 0.00001) ;; signaling errors: (define (perimeter2 a-shape) (cond [(square? a-shape) (* (square-length a-shape) 4)] [(circle? a-shape) (* (* 2 (circle-radius a-shape)) pi)] [else (error "a shape expected")] ;; a meaningful error message ) ) ;(perimeter2 42) ;; using check-error to check for an error (check-error (perimeter2 42) "a shape expected") ;; Exercise 7.1.3: develop the function called area, which consumes ;; either a circle or a square and computes the area. ;; Define a function that finds a middle point between two ;; positions and returns it as a position. ;; If the function is given inputs that are not positions, ;; it should signal an error. ;; Write tests for the function, including tests for errors.