So far we've just used the Listener as a calculator, to evaluate expressions. In this lesson we're going to make a huge leap forward and show you how to define your own procedures. Once you've defined a procedure, it has the same status as the built-in procedures, like list and +.
Let's define a procedure to return the average of two numbers.
In words, the procedure for finding the average of two numbers is:
- Add the first number to the second number.
- Divide the sum by 2.
Defining a procedure: defun
To define a procedure you use the special operator defun. This is an abbreviation for define function, but Lisp procedures are not strictly functions in the mathematical sense.
We can write the average procedure as follows:
(defun average (1st-number 2nd-number)
(/ (+ 1st-number 2nd-number) 2))
The first argument to defun gives the name of the procedure, which we've chosen as average.
The second argument, (1st-number 2nd-number), is a list of what are called the parameters. These are symbols representing the numbers we are going to refer to later in the procedure.
The rest of the definition, (/ (+ 1st-number 2nd-number) 2), is called the body of the procedure. It tells Lisp how to calculate the value of the procedure, in this case sum the numbers and divide by 2.
The words you use for the parameters are arbitrary, as long as they match the words you use in the procedure definition. So you could equally well have written the average procedure as follows:
(defun average (a b)
(/ (+ a b) 2))
To define it we can type the definition at the Lisp prompt:
CL-USER > (defun average (1st-number 2nd-number) (/ (+ 1st-number 2nd-number) 2)) AVERAGE
Alternatively you could type the definition into the Lisp Editor and select Compile Buffer to evaluate it.
We can try it out with:
CL-USER 13 > (average 7 9)
CL-USER 14 > (average (+ 2 3) (+ 4 5))
Remember that the arguments are evaluated before they are given to the procedure.
Procedures without parameters
A procedure doesn't have to have any parameters. Here's a procedure dice that returns a random dice throw from 1 to 6:
(defun dice () (+ 1 (random 6)))
To call the procedure you simply write:
CL-USER 10 > (dice) 5
1. Square a number
Define a procedure square that returns the square of a number. Check that:
2. Find the nth triangular number
Define a procedure triangular that gives the nth triangular number defined as n(n+1)/2, and check that:
3. Find the result of throwing two dice
Define a procedure two-dice that returns the total result of throwing two dice.
blog comments powered by Disqus