Lisp - Functions as Return Values



In LISP, capability of a function to return a function makes it a very powerful language. LISP is a functional programming language where functions are first class objects means a LISP function can acts as another data type (numbers, strings). A function exihibits following capabilities −

  • 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

Functions are First Class Objects

As LISP treats a function in same way as data we can pass a function as an argument to another function. We can return a function as a result of a function and can assign a function to a variable.

Closure

When a function is returning another function, the returned function "closes over" the returning function. Which means returned function can access the variables and binding of its creational environment even if enclosing function is executed. The returned function is termed as Closure.

Higher Order Function

A function which can take other function as an argument is termed as Higher Order Function. A higher order function is very commonly used feature in LISP.

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

Example - Returning Function from a function

main.lisp

; return a function to add x to passed argument
(defun adder (x)
  (lambda (y) (+ x y)))

; return a function to multiply x to passed argument
(defun multiply (x)
  (lambda (y) (* x y)))
  
; create a function to add 5
(defvar add5 (adder 5))

; create a function to multiply by 5
(defvar multiply-by-5 (multiply 5))

; call add5 to 10; evaluates to 15
(print(funcall add5 10))

; call multiply-by-5 to 10; evaluates to 50
(print(funcall multiply-by-5 10))

Output

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

15 
50  

Key Considerations

  • Flexible Code − By returning a function, we can create a flexible and reusable, generic code enhancing the reusablity.

  • Functional Programming − Core functional concepts like mapping, filtering, reducing works best with lambda expressions.

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

Advertisements