Lisp - functions



A function is a group of statements that together perform a task.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.

Defining Functions in LISP

The macro named defun is used for defining functions. The defun macro needs three arguments −

  • Name of the function
  • Parameters of the function
  • Body of the function

Syntax for defun is −

(defun name (parameter-list) "Optional documentation string." body)

Let us illustrate the concept with simple examples.

Example

Let's write a function named averagenum that will print the average of four numbers. We will send these numbers as parameters.

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; define a function to get average of four numbers
(defun averagenum (n1 n2 n3 n4)
   (/ ( + n1 n2 n3 n4) 4)
)
; call the function and print the result
(write(averagenum 10 20 30 40))

Output

When you execute the code, it returns the following result −

25

Example

Let's define and call a function that would calculate the area of a circle when the radius of the circle is given as an argument.

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; define a function to caculate area of circle
(defun area-circle(rad)
   ;Calculates area of a circle with given radius
   ; terminate printing 
   (terpri)
   ; print the radius
   (format t "Radius: ~5f" rad)
   ; print the area
   (format t "~%Area: ~10f" (* 3.141592 rad rad))
)
(area-circle 10)

Output

When you execute the code, it returns the following result −

Radius:  10.0
Area:   314.1592

Points to Consider

Please note that −

  • You can provide an empty list as parameters, which means the function takes no arguments, the list is empty, written as ().

  • LISP also allows optional, multiple, and keyword arguments.

  • The documentation string describes the purpose of the function. It is associated with the name of the function and can be obtained using the documentation function.

  • The body of the function may consist of any number of Lisp expressions.

  • The value of the last expression in the body is returned as the value of the function.

  • You can also return a value from the function using the return-from special operator.

Related Concepts

Let us discuss the above concepts in brief. Click following links to find details −

Advertisements