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 five key parts to this function definition:
Name: the name of the function (in this case,
Inputs: what data the function needs (in this case,
Contract: the first line, which summarizes what kind of data the program inputs and outputs
Purpose: the second line, which describes what operation the program performs
Body: the computation that produces the output using the
input (in this case
(/ (+ num1 num2) 2)).
The number of inputs in the definition should match the number of inputs that the contract 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.
Why do we create functions (aka our own operators) in programming?
(define size 10) do? Is
size a function? If so, what does the function take as
input and output? If not, what is it?
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
num2. What would
happen if you gave this to DrScheme and why? (think before you try
it). What does this teach you about naming inputs?
Where are the names that you used for inputs visible? If
you're not sure, put the
average function in the
definitions window of DrScheme and then type
num1 at the
prompt in the bottom window; what happens and why?
How do you decide which inputs you need for a function?
What's a good way to figure out what the body should look like?
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) (cond [(<= numpens 10) .75] [(> numpens 10) .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 Scheme know how to match up
these numbers between the functions if they don't use the same
Try the exercises for section 3.1 in the text. They help you break a larger problem into smaller functions.