Lisp - Call Functions using apply



apply is a function which enables us to call a function or operator on a list of arguments. apply function is similar to funcall with the difference of arguments passing. apply function requires a list of arguments whereas funcall takes arguments individually. apply function call is useful on a generated list of arguments to be passed to a function.

Syntax - apply function

(apply function-object argument-list)

Where

  • function-object− a function to be called.

    • We can use operator symbols like '+, function name like 'compute or built-in construct like 'list etc.

    • We can use lambda expression as an anonymous function.

    • We can use function object returned by function.

  • argument-list− a list of arguments to be passed to the function to be called.

apply function is very valuable when number of arguments is not known while calling a function or arguments are generated at runtime.

Example - Calling a named function

main.lisp

; call + operator
(print(apply '+ '(2 3)))

; create a new list
(print(apply 'list '(1 2 3)))

; define a function
(defun multiply (x y z) (* x y z))

(terpri)

; call named function
(print(apply 'multiply '(1 2 3)))

Output

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

5 
(1 2 3) 
6 

Example - Using variable to store function

main.lisp

; define a function
(defun multiply-by-two (x) (* x 2))

; set operation as +
(setf operation '+)
; call the function; evaluates to 9
(print(apply operation '(4 5))) 

(terpri)

; set operation to function name
(setf operation 'multiply-by-two)
; call function; evaluates to 12
(print(apply operation '(6))) 

Output

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

9
12 

Example - Calling lambda expression

main.lisp

; call a lambda expression; evaluates to 12
(print(apply (lambda (x y) (* x y)) '(3 4)))

Output

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

12 

Key Considerations

  • apply function is different from funcall function in passing the arguments.

  • apply function takes a list of arguments whereas funcall function uses individual arguments.

  • apply function can be used when arguments are generated dynamically and are present in form of a list.

Advertisements