Functions in Lisp: Defining and Calling

May 23, 2024

Discover the power of functions in Lisp. This post will guide you through defining functions, passing arguments, and calling functions to execute specific tasks in your Lisp programs.

Defining Functions in Lisp

In Lisp, functions are defined using the defun keyword followed by the function name and its parameters. Here’s an example of a simple function that adds two numbers:

(defun add (a b)
    (+ a b))

In this example, the function add takes two parameters a and b and returns their sum using the + operator.

Calling Functions in Lisp

Once a function is defined, you can call it by simply writing its name followed by the arguments enclosed in parentheses. Here’s how you can call the add function defined earlier:

(add 5 3)

This will return the result 8 by adding the numbers 5 and 3.

Passing Arguments to Functions

Functions in Lisp can take multiple arguments separated by spaces. You can also pass expressions as arguments. Here’s an example of a function that calculates the square of a number:

(defun square (x)
    (* x x))

You can call the square function with an expression as an argument like this:

(square (+ 3 2))

This will return the result 25 by squaring the sum of 3 and 2.

Functions are essential in Lisp programming as they help in organizing code, promoting reusability, and enhancing the modularity of your programs. Experiment with defining and calling functions in Lisp to explore its full potential!