Returning Values Functions in LISP
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.
In this function body, our last expression is:
( * n 2)
Hence this function will return the value of this expression when it is called
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
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.
10 20 20
Please Login to comment...