Lisp - Call Functions using funcall



funcall is a very powerful function to call a function by its name or its object stored in a variable. funcall function is very useful in case of first class functions and it helps to determine a function to call at runtime. In this chapter, we'll explore ways to use funcall function.

Syntax - funcall function

(funcall function-object arg1 arg2 ...)

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.

  • arg1, arg2, ...− arguments to be passed to the function to be called.

Example - Calling a named function

main.lisp

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

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

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

(terpri)

; call named function
(print(funcall 'multiply-by-two 5))

Output

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

5 
(1 2 3) 
10 

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(funcall operation 4 5)) 

(terpri)

; set operation to function name
(setf operation 'multiply-by-two)
; call function; evaluates to 12
(print(funcall 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(funcall (lambda (x y) (* x y)) 3 4))

Output

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

12 

Example - Creating a High Order Function

main.lisp

; define a high order function
(defun apply-operation (function arg1 arg2)
  (funcall function arg1 arg2))

; call the + operator; evaluates to 15
(print(apply-operation '+ 10 5)) 
(terpri)
; call the * operator; evaluates to 50
(print(apply-operation '* 10 5))
(terpri)
; call a lambda expression; evaluates to 5
(print(apply-operation (lambda (a b) (/ a b)) 10 2))

Output

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

15 
50 
5 

Key Considerations

  • funcall function can be used to create high order functions which can take functions as arguments.

  • funcall function treats functions as first class objects.

  • funcall function is very useful in dynamic function dispatching.

Advertisements