Review on Functions


Terminology Review

Consider the following function definition

   ;; average : Number Number -> Number
   ;; consumes two numbers and produces their average
   (define (average num1 num2)
     (/ (+ num1 num2) 2))

There are four key parts to this function definition:

The number of inputs in the definition should match the number of inputs that the signature lists. Always use descriptive names for the inputs, as they make the computation easier to read and write.

For a more detailed review, reread Section 2 and Section 3 up through 3.1 in the text.


Study Questions

  1. Why do we create functions (aka our own operators) in programming?

  2. What does (define size 10) do? Is size a function? If so, what does the function take as input and output? If not, what is it?

  3. Assume that your first try at the average program looked like the following:

       ;; average : Number Number -> Number
       ;; consumes two numbers and produces their average
       (define (average number number)
         (/ (+ number number) 2))
    

    In other words, you used the word number for both inputs instead of num1 and num2. What would happen if you gave this to DrRacket and why? (think before you try it). What does this teach you about naming inputs?

  4. Where are the names that you used for inputs visible? If you're not sure, put the average function in the definitions window of DrRacket and then type num1 at the prompt in the bottom window; what happens and why?

  5. How do you decide which inputs you need for a function?

  6. What's a good way to figure out what the body should look like?

  7. Recall our pen programs from classs:

    ;; single-pen-cost : Number -> Number
    ;; consumes a number of pens and produces the cost of one pen
    (define (single-pen-cost numpens)
      (if (<= numpens 10) 
          .75
          .50)))
    
    
    ;; pen-order-cost : Number -> Number
    ;; consumes a number of pens and produces cost to order that many pens
    (define (pen-order-cost number-of-pens)
      (* number-of-pens (single-pen-cost number-of-pens)))
    

    Note that one function uses numpens while another uses number-of-pens. How does DrRacket know how to match up these numbers between the functions if they don't use the same names?

  8. Try the exercises for section 3.1 in the text. They help you break a larger problem into smaller functions.