Lisp - Lambda Functions



At times you may need a function in only one place in your program and the function is so trivial that you may not give it a name, or may not like to store it in the symbol table, and would rather write an unnamed or anonymous function.

LISP allows you to write anonymous functions that are evaluated only when they are encountered in the program. These functions are called Lambda functions.

You can create such functions using the lambda expression. The syntax for the lambda expression is as follows −

(lambda (parameters) body)

A lambda form cannot be evaluated and it must appear only where LISP expects to find a function.

Example

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; create a lambda expression and print the result
(write ((lambda (a b c x)
   (+ (* a (* x x)) (* b x) c))
   4 2 9 3)
)

Output

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

51

Example

Update the source code file named main.lisp and type the following code in it.

main.lisp

; create a lambda expression and print the result
(write ((lambda (a b c x)
   (+ a b c x))
   4 2 9 3)
)

Output

When you execute the code, it returns the following result as sum of passed arguments −

18

Example

Update the source code file named main.lisp and type the following code in it.

main.lisp

; create a lambda expression and print the result
(write ((lambda (a b c x)
   (* a b c x))
   4 2 9 3)
)

Output

When you execute the code, it returns the following result as product of passed arguments −

216
lisp_functions.htm
Advertisements