90 likes | 333 Views
Returning values from functions. You can return a value from a function by using the built-in function : ( return-from Function_name value ) For example: (defun plus (x y) (setq answer (+ x y)) (return-from plus answer) ) (setq result (plus 10 20)). Block.
E N D
Returning values from functions • You can return a value from a function by using the built-in function : (return-from Function_name value) • For example: (defun plus (x y) (setq answer (+ x y)) (return-from plus answer) ) (setq result (plus 10 20))
Block • You can also group expressions together in a structure called block. • For example: (block justablock (format t “10 + 11 is ~D” (+ 10 11)) ) • A block is used to demarcate a group of expressions that achieves a certain result. • You can return values from blocks just as you do with functions.
nil block • The blocks in the previous slides are called named blocks. • You can also have blocks which are labeled nil. For example, loops are default labeled nil. • Here is another example of a nil block. (block nil (print “This is a nil block”) (return “End of block”) ) • To return a value from a nil block, use (return value)
Funcall • An example of this would be: (funcall #’+ 1 99) • Notice that #’ is used to denote a function. In this case + is the required function. • Funcall calls its first argument on its remaining arguments. • This is an example of a function that takes another function as one of its arguments.
Apply • An example of this function is as follows: (apply #’+ 1 99 ‘(5 6)) • The above is similar to(+ 1 99 5 6) • This is similar to funcall except that its final argument should be a list. The elements of that list are treated as additional arguments to funcall.
When to use these? • These two functions are very useful when their first argument is a variable. This means you may have more than one function that is applicable on a set of arguments. • For example, to find the shortest distance in a network, you may have several possible algorithms to perform the search. These algorithms are written as functions. • Hence, you can use apply or funcall to specify the desired function (algorithm) to perform the search.
Mapcar • This is another interesting function that takes a function of one argument and a list. It works by • applying the function to each element of the list, and • collects the results in a list and return them. • For example, (mapcar #’sqrt ‘(1 4 9 16 25)) (mapcar #’first ‘((a b) (c d) (e)))
Lambda • If you want to create a temporary function and do not want to name it, then use lambda. For example: #’(lambda (x) (* 8 x)) • To call the above defined lambda function, do as follows: (funcall * 5)