According to one survey, teenage boys spend an average of 32% of their allowance on food, while teenage girls spend 26% on average. If a boy and a girl each receive n dollars, how much more does the boy spend on food? Write three functions: the first consumes an amount of allowance and returns how much a boy spends on food. The second consumes an amount of allowance and returns how much a girl spends on food. The third consumes an allowance amount and returns the difference between how much a boy and a girl spend on food.Let's write a contract, examples, header, and template for each function:
; boy-food-budget : num (allowance) => num ; Ex: (boy-food-budget 10.00) => 3.20 ; Ex: (boy-food-budget 0) => 0 (define (boy-food-budget allowance) ( ... allowance ... )) ; girl-food-budget : num (allowance) => num ; Ex: (girl-food-budget 10.00) => 2.60 ; Ex: (girl-food-budget 0) => 0 (define (girl-food-budget allowance) ( ... allowance ... )) ; food-budget-difference : num (allowance) => num ; Ex: (food-budget-difference 10.00) => 0.60 ; Ex: (food-budget-difference 0) => 0 (define (food-budget-difference allowance) ( ... allowance ... ))
Now we have to come up with bodies for these functions. As suggested (and in keeping with the principle of "top-down design, bottom-up coding and testing"), we'll start with boy-food-budget and girl-food-budget, and only after these are tested and debugged will we go on to food-budget-difference.
(define (boy-food-budget allowance) (* allowance 0.32))We test this on its examples, confirm that it works in every case, and declare it finished.
(define (girl-food-budget allowance) (* allowance 0.26))Ditto.
Next we'll write the body for the food-budget-difference function. We already have functions to find how much each kid spends on food, so we just need to subtract them:
(define (food-budget-difference allowance) (- (boy-food-budget allowance) (girl-food-budget allowance)))We test this on its examples, confirm that it works in every case, and declare it finished.