Lisp - Returning Value from Function
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
Create a new source code file named main.lisp and type the following code in it.
main.lisp
; define a function add-all which will return sum of passed numbers (defun add-all(a b c d) (+ a b c d) ) ; set sum as result of add-all function (setq sum (add-all 10 20 30 40)) ; print value of sum (write sum) ; terminate printing (terpri) ; print value of result of add-all function (write (add-all 23.4 56.7 34.9 10.0))
Output
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
Update the source code file named main.lisp and type the following code in it −
main.lisp
; define a function to return a number as 10 (defun myfunc (num) (return-from myfunc 10) num ) ; print result of function call (write (myfunc 20))
Output
When you execute the code, it returns the following result −
10
Change the code a little −
main.lisp
; define a function to return a number as 10 (defun myfunc (num) (return-from myfunc 10) write num ) ; print result of function call (write (myfunc 20))
Output
It still returns −
10
lisp_functions.htm
Advertisements