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 functions. Once you've defined a function, it has the same status as the built-in functions, like list and +.
Let's define a function to return the average of two numbers.
In words, the function 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 function you use the special operator defun. We can write the average procedure as follows:
(defun ave (n1 n2)
(/ (+ n1 n2) 2))
The first argument to defun gives the name of the function, which we've chosen as ave.
The second argument, (n1 n2), is a list of what are called the parameters. These are symbols representing the numbers we are going to refer to later in the function.
The rest of the definition, (/ (+ n1 n2) 2), is called the body of the function. It tells Lisp how to calculate the value of the function, in this case sum the numbers and divide by 2.
The symbols you use for the parameters are arbitrary, as long as they match the symbols you use in the function definition. So you could equally well have written the ave procedure as follows:
(defun ave (a b)
(/ (+ a b) 2))
To define it we can type the definition at the uLisp prompt:
> (defun ave (n1 n2) (/ (+ n1 n2) 2)) ave
We can try it out with:
> (ave 7 9)
> (ave (+ 2 3) (+ 4 5))
Because uLisp works with integers the result will be rounded down to the nearest integer.
Functions without parameters
A function doesn't have to have any parameters. Here's a function die that returns a random dice throw from 1 to 6:
(defun die () (+ 1 (random 6)))
To call the function you simply write:
> (die) 5
1. Square a number
Define a procedure sq that returns the square of a number. Check that:
2. Find the nth triangular number
Define a procedure tri 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 di2 that returns the total result of throwing two dice.