Working with Lists in Lisp

May 24, 2024

Lists are a fundamental data structure in Lisp, offering a powerful way to store and manipulate collections of data. In this post, we will explore how to work with lists in Lisp, including creating lists, accessing elements, and performing various operations on lists.

Creating Lists

In Lisp, lists are constructed using parentheses to enclose elements separated by spaces. For example, a simple list of numbers can be created as follows:

(setq my-list '(1 2 3 4 5))

This creates a list named my-list containing the numbers 1, 2, 3, 4, and 5.

Accessing Elements

To access elements in a list, you can use the car and cdr functions. The car function returns the first element of a list, while the cdr function returns the rest of the list after the first element. For example:

(car my-list) ; Returns 1
(cdr my-list) ; Returns (2 3 4 5)

Manipulating Lists

Lists in Lisp are immutable, meaning that once a list is created, its elements cannot be changed. However, you can manipulate lists by creating new lists based on existing ones. For example, you can add elements to the front of a list using the cons function:

(setq new-list (cons 0 my-list)) ; Adds 0 to the front of my-list

Iterating Over Lists

You can iterate over the elements of a list using recursion and conditional statements. For example, to calculate the sum of all elements in a list, you can define a recursive function like this:

(defun sum-list (lst)
  (if (null lst)
      0
      (+ (car lst) (sum-list (cdr lst)))))

(sum-list my-list) ; Returns the sum of elements in my-list

Working with lists in Lisp opens up a world of possibilities for data manipulation and processing. By mastering the intricacies of lists, you can write elegant and efficient Lisp programs that leverage the power of this versatile data structure.