Here are the exercises and my solotions of Section 2.3, called "Word Problems", in How to Design Programs.
Exercise 2.3.1.
Utopia's tax accountants always use programs that compute income taxes even though the tax rate is a solid, never-changing 15%. Define the program tax, which determines the tax on the gross pay.
Also define netpay. The program determines the net pay of an employee from the number of hours worked. Assume an hourly rate of $12.
Solution
The gross pay is
gross = 12 * h
the tax is 15% of the gross pay, or
tax = gross * 0.15
The net pay is gross pay minus tax, or
netpay = grosspay - tax
This means that both tax and net pay are depending on the number of hours worked.
(define (grosspay h)
(* h 12))
(define (tax h)
(* (grosspay h) 0.15))
(define (netpay h)
(- (grosspay h) (tax h)))
Exercise 2.3.2.
The local supermarket needs a program that can compute the value of a bag of coins. Define the program sum-coins. It consumes four numbers: the number of pennies, nickels, dimes, and quarters in the bag; it produces the amount of money in the bag.
Solution
This is really easy:
value = pennies * 1 + nickels * 5 + dimes * 10 + quorters * 25
or in DrScheme:
(define (sum-coins p n d q)
(+ p (+ (* n 5) (+ (* d 10) (* q 25)))))
Exercise 2.3.3.
An old-style movie theater has a simple profit function. Each customer pays $5 per ticket. Every performance costs the theater $20, plus $.50 per attendee. Develop the function total-profit. It consumes the number of attendees (of a show) and produces how much income the attendees produce.
Solution
Each performances brings in a revenue of:
revenue = attendees * 5
The performance costs are:
cost = 20 + attendees * 0.5
The profit is:
profit = revenue - cost
or in DrScheme:
(define (revenue n)
(* n 5))
(define (cost n)
(+ 20 (* n 0.5)))
(define (total-profit n)
(- (revenue n) (cost n)))
No comments:
Post a Comment