A mail-order company charges a shipping cost based on the number of items you order. If you order 3 or fewer items, the cost is $2 per item. If you order 4 items but less than 10 items, it is only $1.10 per item. But if you order 10 or more items, there is a flat fee of $12.Again, there are several cases to be considered. The data analysis step shows us three cases:Write a function which takes a number of items and returns the total shipping cost.
Now we'll write a contract, examples, header, and template for the function:
; shipping-charge : num (items) => num (shipping-charge) ; Ex: (shipping-charge 0) => 0 ; Ex: (shipping-charge 2) => 4 ; Ex: (shipping-charge 3) => 6 ; Ex: (shipping-charge 4) => 4.40 ; Ex: (shipping-charge 6) => 6.60 ; Ex: (shipping-charge 9) => 9.90 ; Ex: (shipping-charge 10) => 12 ; Ex: (shipping-charge 20) => 12 (define (shipping-charge items) (cond [ question answer ] [ question answer ] [ question answer ]))Note that we listed an example for each case, as well as examples on both sides of each "borderline". I've also included 0 as a potentially special case, since it often is. If you're not convinced that all these "expected answers" are correct, go back and read the problem again. If you're still not convinced, maybe I've misinterpreted the problem.
Next we fill in the questions:
(define (shipping-charge items) (cond [(<= items 3) answer ] [(< items 10) answer ] [(>= items 10) answer ]))and then the answers:
(define (shipping-charge items) (cond [(<= items 3) (* 2 items) ] [(< items 10) (* 1.10 items) ] [(>= items 10) 12 ]))Note that in the first two cases, the "answer" called for further computation; in the third case, the answer is a simple $12.
We now test this on each example:
(shipping-charge 0)
0
(shipping-charge 2)
4
(shipping-charge 3)
6
(shipping-charge 4)
4.4
(shipping-charge 6)
6.6
(shipping-charge 9)
9.9
(shipping-charge 10)
12
(shipping-charge 20)
12
Looks good!