Lisp - Functions as Arguments



LISP functions are first class objects means a LISP function can acts as another data type (numbers, strings).

  • Assignable to Variable− A function can be assigned to a variable and then called via that variable.

  • Can be passed as Arguments− A function can be passed as an input to another function.

  • Can be returned from a Function− A function can be returned as a result of invocation of a function.

Key Concepts

First Class Function

As LISP treats a function in same way as data we can pass a function as an argument to another function.

Higher Order Function

A function which can take other function as an argument is termed as Higher Order Function.

LISP provides many useful built-in higher order function like mapcar, apply, funcall etc.

Lambda Expressions

A Lambda expression is used to define an anonymous function. We can use a lambda expression as well to be passed as an argument in case function is simple to implement as a lambda expression.

Passing a Named Function as Argument

main.lisp

; define a function to act on 5 as argument
(defun work-on-five (func)
  (funcall func 5))

; define a function to get square of a number
(defun square (x) (* x x))

; define a function to get cube of a number
(defun cube (x) (* x x x))

; apply square funtion on 5
(print(work-on-five 'square))
(terpri)
; apply cube funtion on 5
(print(work-on-five 'cube))

Output

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

25
125

Here work-on-five is a higher order function. square and cube are functions to be passed as arguments. funcall calls the passed function as argument.

Passing a Lambda Expression as Argument

main.lisp

; define a function to apply passed function on the list
(defun work-on-list (func lst)
  (mapcar func lst))

; Multiply each element of list by 2. Evaluates to (2 4 6)
(print(work-on-list (lambda (x) (* x 2)) '(1 2 3))) 

Output

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

(2 4 6)

Here lambda expression is used to multiply each element of passed list by 2. mapcar applies the lambda expression to each element of the list.

Key Considerations

  • Flexible Code − By passing a function as argument, coding can be more flexible and generic enhancing the reusablity.

  • Functional Programming − Core functional concepts like mapping, filtering, reducing works best with functions as arguments.

  • Event Handling − Callback functions are executed when an event occurs. By passing function as arguments, it becomes easier to do event handling with concept of callback functions.

Advertisements