Programmers create programs like authors write books. We first decide what the program needs to do, then create an outline.
After writing the entire program definition, we test the program to verify it works.
Write the contract
Write the header
State the purpose
Provide examples
Write the body
Test the function
Example - Hypotenuse of a right triangle
Write a function to find the length of the hypotenuse of a right triangle.
The Pythagorean Theorem shows the relationship among the sides of a right triangle.
$$c^2=a^2+b^2$$
$$c= \sqrt{a^2+b^2}$$
1. Contract
Write a function definition, showing just the name of the function, what it consumes, and what it produces.
;; hypotenuse-length: number number -> number
2. Header
Show the name of the function, and its parameters.
(define (hypotenuse-length a b) ... )
3. Purpose
State the purpose in your own words.
;; function to calculate the hypotenuse of a right triangle, given its legs, using the Pythagorean Theorem
Complete the function definition by writing a legal expression. See notes below on writing the body.
(define (hypotenuse-length a b)
(sqrt (+ (* a a) (* b b))))
6. Testing
Use the interactions window and your examples from step 4 to verify the function produces the correct output.
Writing the body
Writing the body is usually the most difficult part of creating a program. Here are some steps to help if you get stuck:
Draw a picture
Write the formula you used to provide examples
Draw the circle of evaluation for the formula
Write the legal expression from the circle of evaluation
Exercise 3.4
Apply the design recipe to each of the following problems.
Find the area of a rectangular border that surrounds a patio, given the length and width of the patio, and the width of the border.
Find the area of a ring, given it's inner and outer radius.
Convert from inches to centimeters. There are 2.54 centimeters per inch.
Convert from feet to centimeters. centimeters = feet × 12 × 2.54
Compute the cost of driving, given miles per gallon of a vehicle, and the price per gallon of gas, and number of miles driven.
cost = (price per gallon / miles per gallon) × miles driven
Compute the profit from selling t-shirts, given the number of t-shirts, cost of each t-shirt, and sales price of each t-shirt.
The profit for one t-shirt = sales price - cost.
Challenge Exercise 3.4x
A standard race track surrounds a rectangular field, as shown in the diagram. It has two straight segments, and two semi-circle segments at each end of the rectangle.
Find the area of the track, given the dimensions of the rectangular field and the width of the track.
Computer Programming Unit 3.3 - Designing Functions for a Purpose