Functions in Lisp
Functions are central in Lisp. We’ll learn about functions with a few different examples.
To run this Lisp program, you would typically save it to a file (e.g., functions.lisp
) and then load it into a Lisp interpreter or compile and run it, depending on your Lisp implementation.
For example, using SBCL (Steel Bank Common Lisp):
In Lisp, functions are first-class citizens, meaning they can be passed as arguments, returned from other functions, and assigned to variables. This makes Lisp particularly powerful for functional programming paradigms.
Lisp doesn’t require explicit type declarations for function parameters or return values, as it’s dynamically typed. However, some Lisp dialects and implementations support optional type declarations for optimization or documentation purposes.
The defun
special form is used to define functions in Lisp. The general syntax is (defun function-name (parameters) body)
.
Lisp uses prefix notation, where the function name comes before its arguments, enclosed in parentheses. This is different from many other languages but allows for powerful macro systems and code-as-data paradigms that Lisp is known for.
There are several other features to Lisp functions, including multiple return values, optional parameters, and keyword arguments, which we might explore in subsequent examples.