Representing two-dimensional arrays in uLisp


#1

For some applications the most appropriate way to represent the data is as a two-dimensional array. Although uLisp doesn’t provide direct support for arrays, the following example shows how it’s easy to implement two-dimensional arrays using lists.

First we need a function to construct an empty array. Here is a function makearray that recursively creates an x by y array and returns it. It uses a helper function makelist:

(defun makearray (x y e)
  (makelist x (makelist y e)))

(defun makelist (n e)
  (if (zerop n) nil (cons e (makelist (1- n) e))))

The third parameter, e, specifies the initial value of each element. Here’s an example of its use:

> (defvar c (makearray 3 4 0))
c

> c
((0 0 0 0) (0 0 0 0) (0 0 0 0))

To access an arbitrary element of a two-dimensional array we use arrayref:

(defun arrayref (a x y)
  (nth y (nth x a)))

Changing an arbitrary element is a bit trickier. Here’s one way using a function changearrayref, which uses a recursive helper function changenth:

(defun changearrayref (a x y n)
  (changenth a x
             (changenth (nth x a) y n)))

(defun changenth (list x n)
  (if (null list) nil
    (cons 
     (if (zerop x) n (car list))
     (changenth (cdr list) (1- x) n))))

Here’s an example of its use on the array c we defined above:

> (changearrayref c 1 2 7)
((0 0 0 0) (0 0 7 0) (0 0 0 0))

Note that this is non-destructive; c still has its original value:

> c
((0 0 0 0) (0 0 0 0) (0 0 0 0))