Google News
logo
Lisp - Interview Questions
How are functions defined in Lisp? Describe the syntax.
In Lisp, functions are defined using the `defun` special form. The `defun` form is used to create a named function with a specified set of parameters and a function body. Here is the syntax for defining functions in Lisp :
(defun function-name (parameter-list)
  "Optional documentation string"
  function-body)​

Let's break down each component of the `defun` form :

* `defun`: It is a special form in Lisp used to define functions.

* `function-name`: This is the name of the function being defined. It can be any valid Lisp symbol.

* `parameter-list`: It is a list of parameters that the function accepts. Each parameter is also a symbol and is enclosed in parentheses. The parameters represent the inputs to the function.

* `"Optional documentation string"`: This is an optional string that provides documentation or a description of the function. It is typically used for documentation purposes and can be accessed using the `documentation` function.

* `function-body`: It is the body of the function, consisting of one or more Lisp expressions. The function body is enclosed in parentheses. These expressions define what the function does when called, including any calculations, control flow, or side effects.
Here's an example to illustrate the syntax of defining a function in Lisp :
(defun square (x)
  "Calculates the square of a number."
  (* x x))​

In this example, we define a function named `square` that takes a single parameter `x`. The function body, `(* x x)`, multiplies `x` by itself, effectively calculating the square of `x`. The optional documentation string provides a brief description of what the function does.

Once a function is defined, it can be called like any other Lisp function using parentheses. For example, `(square 5)` would call the `square` function with the argument `5` and return `25`.

Defining functions using the `defun` syntax allows for the creation of reusable code and modular programming in Lisp. Functions can be defined once and called multiple times with different arguments, making the development of complex programs more manageable and structured.
Advertisement