Monday, 22 March 2010

Writing A Function In Lisp

There are a large number of built in functions in Lisp, it's also possible, useful and very easy to write your own functions in Lisp. Have a look at this function:

(defun my-square (x)
(* x x))

Let's break this down:

defun is a function used to define new functions.
my-square is the name that we've given to our function, we could call it almost anything we like but it makes to give it a useful name so that we can remember it later.
x is the argument or input to our function. Again we could call this almost anything we like.
(* x x) This is where the actual work of our function takes place, we using the multiply function and multiplying x by itself.

When you have written and evaluated this function, it can be called and used just any other function:
(my-square 5)
25

(my-square 9)
81

It's good practice to comment your function, both so that others can understand it quickly and easily and for yourself.

(defun my-square (x)
 "this function squares an input number x"
(* x x))

Using double quotes " " adds a definition to your function, these can only be used after you have defined the input arguments.

A more versatile way of adding comments that can be used anywhere is to use semicolons, anything after the semicolon is ignored:

(defun my-square (x)
 "this function squares an input number x"

(* x x)) ; this line squares x

We'll work more on writing new functions tomorrow, for now see if you can write these functions, answers in tomorrow's post:

minus-one a function that takes a single number as input and returns the number that is one less
ten-times-bigger a function that takes a single number as input and returns the number that is ten times bigger
weeks-to-days a function that takes a number of weeks as input and returns the total number of equivalent days

These examples may seem simple, however this is a really good stepping stone to learn how to build much more powerful functions in Lisp. Answers and more on building functions tomorrow...