List Operations: The Dance of Data and Code

In Lispex, a list is not merely a data structure; it is the representation of the code itself. The art of manipulating lists is like weaving the flow of thought, giving structure to data, and breathing dynamic life into code.

This page provides a reference for built-in functions that create or manipulate lists in Lispex. These complement the functions found in the Core Functions reference.


cons

Constructs a new list by adding an element to the front of an existing list. "Cons" is short for "construct".

  • Syntax: (cons ELEMENT LIST)
  • Arguments:
    • ELEMENT: The new element to add to the front.
    • LIST: The existing list to which the element will be added.
  • Returns: A new list.
  • Throws: A RuntimeError if the second argument is not a list.

Example:

(cons 1 (list 2 3 4))
;; Result: (list 1 2 3 4)

(cons (list "a") (list "b" "c"))
;; Result: (list (list "a") "b" "c")

append

Appends two lists together to create a new, single list.

  • Syntax: (append LIST_1 LIST_2)
  • Arguments:
    • LIST_1: The first list.
    • LIST_2: The second list.
  • Returns: A new list containing all elements from LIST_1 followed by all elements from LIST_2.
  • Throws: A RuntimeError if either argument is not a list.

Example:

(append (list 1 2) (list 3 4))
;; Result: (list 1 2 3 4)

(append (list) (list 1 2))
;; Result: (list 1 2)

nth

Returns the element at a specific zero-based index in a list.

  • Syntax: (nth LIST INDEX)
  • Arguments:
    • LIST: The list from which to retrieve an element.
    • INDEX: The integer index of the element to retrieve (starting from 0).
  • Returns: The element at the specified index.
  • Throws:
    • A RuntimeError if LIST is not a list or INDEX is not an integer.
    • A RuntimeError if INDEX is out of bounds (less than 0 or greater than or equal to the list's length).

Example:

(define my-list (list "a" "b" "c"))

(nth my-list 0)
;; Result: "a"

(nth my-list 2)
;; Result: "c"

(nth my-list 3)
;; Throws RuntimeError: Index 3 out of bounds