LISP – Functions

  • Post author:
  • Post category:LISP
  • Post comments:6 Comments
LISP - Functions

This topic is about 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 1

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.

(defun averagenum (n1 n2 n3 n4)
   (/ ( + n1 n2 n3 n4) 4)
)
(write(averagenum 10 20 30 40))

When you execute the code, it returns the following result โˆ’

25

Example 2

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.

(defun area-circle(rad)
   "Calculates area of a circle with given radius"
   (terpri)
   (format t "Radius: ~5f" rad)
   (format t "~%Area: ~10f" (* 3.141592 rad rad))
)
(area-circle 10)

When you execute the code, it returns the following result โˆ’

Radius:  10.0
Area:   314.1592

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.

Let us discuss the above concepts in brief. Click following links to find details โˆ’

In this topic we learned about LISP – Functions. To learn more, Click Here.

This Post Has 6 Comments

Leave a Reply