Arrays in Lisp

Our first example demonstrates how to work with arrays in Lisp. Arrays are sequences of elements with a fixed size.

(defun main ()
  ;; Here we create an array 'a' that will hold exactly 5 integers.
  ;; By default, an array is initialized with nil values.
  (let ((a (make-array 5 :initial-element 0)))
    (format t "emp: ~a~%" a)

    ;; We can set a value at an index using setf, and get a value with aref.
    (setf (aref a 4) 100)
    (format t "set: ~a~%" a)
    (format t "get: ~a~%" (aref a 4))

    ;; The length function returns the length of an array.
    (format t "len: ~a~%" (length a))

    ;; Use this syntax to declare and initialize an array in one line.
    (let ((b #(1 2 3 4 5)))
      (format t "dcl: ~a~%" b))

    ;; In Lisp, we don't have a direct equivalent to Go's [...] syntax,
    ;; but we can create arrays with initial contents easily.
    (let ((b (vector 1 2 3 4 5)))
      (format t "dcl: ~a~%" b))

    ;; To create an array with specific indices set, we can use make-array with :initial-contents
    (let ((b (make-array 5 :initial-contents '(100 0 0 400 500))))
      (format t "idx: ~a~%" b))

    ;; Array types are one-dimensional, but you can create multi-dimensional arrays.
    (let ((twoD (make-array '(2 3) :initial-element 0)))
      (dotimes (i 2)
        (dotimes (j 3)
          (setf (aref twoD i j) (+ i j))))
      (format t "2d: ~a~%" twoD))

    ;; You can create and initialize multi-dimensional arrays at once too.
    (let ((twoD #2A((1 2 3) (1 2 3))))
      (format t "2d: ~a~%" twoD))))

;; Call the main function
(main)

When you run this program, you should see output similar to:

emp: #(0 0 0 0 0)
set: #(0 0 0 0 100)
get: 100
len: 5
dcl: #(1 2 3 4 5)
dcl: #(1 2 3 4 5)
idx: #(100 0 0 400 500)
2d: #2A((0 1 2) (1 2 3))
2d: #2A((1 2 3) (1 2 3))

In Lisp, arrays are typically printed in the form #(v1 v2 v3 ...) for one-dimensional arrays and #2A((v11 v12 v13) (v21 v22 v23)) for two-dimensional arrays.

Note that Lisp arrays are zero-indexed, just like in many other programming languages. The make-array function is used to create arrays with a specified size and optional initial values. The vector function can be used to create one-dimensional arrays with initial values.

For multi-dimensional arrays, we use nested lists to specify the dimensions and initial values. The #2A reader macro is used to create two-dimensional arrays inline.

Lisp provides powerful array manipulation capabilities, and you can perform various operations on arrays using built-in functions and macros.