LISP - Returning Values Functions



By default, a function in LISP returns the value of the last expression evaluated as the return value. The following example would demonstrate this.

Example 1

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

(defun add-all(a b c d)
   (+ a b c d)
)
(setq sum (add-all 10 20 30 40))
(write sum)
(terpri)
(write (add-all 23.4 56.7 34.9 10.0))

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

100
125.0

However, you can use the return-from special operator to immediately return any value from the function.

Example 2

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

(defun myfunc (num)
   (return-from myfunc 10)
   num
)
(write (myfunc 20))

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

10

Change the code a little −

(defun myfunc (num)
   (return-from myfunc 10)
   write num
)
(write (myfunc 20))

It still returns −

10
lisp_functions.htm
Advertisements