Price of Fruit

Exploration 4.5

Suppose a store sells three kinds of fruit, with the following prices.

FruitPrice
Apple$0.55
Bananna$0.72
Orange$1.25

The store owner hires you to write a program that consumes the name of the fruit and produces its price. Write the contract and header for this function on page 75 of your workbook.

Our program must determine which of several conditions is true for the name of the fruit. It will decide what number to produce using a conditional function. Enter the following code in the Definitions Window of DrRacket. Then press run and test your function using the interactions window. ALSO, WRITE THE CODE ON PAGE 75 OF YOUR WORKBOOK.

(define (price fruit)
  (cond
    [(string=? fruit "apple") 0.55]
    [(string=? fruit "bananna") 0.72]
    [(string=? fruit "orange") 1.25]))

The Conditional Function

The general form of the conditional function is

  (cond
    [question answer]
    ...
    [question answer])

Each line after cond is called a clause. The dots indicate the cond function can have any number of clauses. Each question is a Boolean function. The cond function produces the answer for the first question that is true.

The cond can also have an else clause at the end. The cond function will produce the answer of the else clause if none of the no question is true.

Continuing Exploration 4.5

What happens if you type (price "rasin") in the Interactions Window using the program you just created?

Now add an else clause to your function, and test it again. Your function should look like the following:

(define (price fruit)
  (cond
    [(string=? fruit "apple") 0.55]
    [(string=? fruit "bananna") 0.72]
    [(string=? fruit "orange") 1.25]
    [else 999999]))

Exercise 4.3 - Price of Pizza Topping

The cost of pizza toppings are shown in the following table. Use the design recipe to create a function that consumes the name of a topping and produces its price. If the topping is not available, your function should produce -1.

ToppingPrice
cheese$9.00
pepperoni$10.50
sausage$11.25
peppers$8.15
Challenge Exercise 4.4 - Legal Triangles (Exceeds Expectations)

The Triangle Inequality states the sum of any two side lengths of a triangle must be greater than the third side length.

a + b > c

Write a function that consumes three side lengths, a, b, and c, and produces a string: "Legal Triangle" or "Not a Triangle". Use the Design Recipe. Be careful - there are several conditions to check. Your recipe will need more than 3 examples to test.

Computer Programming Unit 4.2 - Making Decisions with Conditional Functions