Open In App

Returning Values Functions in LISP

Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article on the LISP function, we have seen the syntax of defining a function and calling the function by passing some arguments.

Returning values from a function:

In LISP, whatever is the last expression in the body of a function becomes the return value of that function.

Example: Let’s create a function that takes the input parameter of a number and doubles its value.

Lisp




(defun double-the-number (n)
    ( * n 2)
)
  
; Making function calls : 
(write (double-the-number 5))
(terpri)    ;Linebreak
(write (double-the-number 10))
(terpri)
(write (double-the-number 20))
(terpri)


In this function body, our last expression is:

( * n 2)

Hence this function will return the value of this expression when it is called

Output : 

10
20
40

But sometimes we may need to break the condition statements or return the values from the middle of a function in this case the RETURN-FROM special operator is used.

The syntax for using RETURN-FROM:

(return-from place value)

Here, the place is the block of code from which we have to return the specific value, for example, the place would be the name of the current function

Example: In the above LISP code, let’s put a condition where if the number is greater than 10, the function will return the value by doubling the number 10 instead of doubling the original number

Lisp




(defun double-the-number (n)
    (if (> n 10)
        (return-from double-the-number (* 2 10)))
    ( * n 2)
)
  
  
;; Calling the function
(write (double-the-number 5))
(terpri)        ;Linebreak
(write (double-the-number 10))
(terpri)
(write (double-the-number 20))
(terpri)


Here, you can see that in the third function call we have passed the value of 20, but due to our condition, it will double the max value(10), hence with the help of the return-from operator we were able to return the value from a function immediately.

Output : 

10
20
20


Last Updated : 29 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads