This is the first program I have ever written in LISP, and I am completely confused. I need to write a function that returns a list of 5 rows of entries, and each one of these rows is a list of 5 entries. I know that CAR and CDR could be used to return the elements of a specified list, but that's not creating a function to return the list. Any ideas on how I could do this? Thanks in advance!

Dani AI

Generated

: two straightforward approaches will do the job — return a fixed nested list (as suggested) or build the rows at runtime. Do not name your function list; that hides the built-in list function. Also be aware that a quoted literal (the '(…) form) denotes a constant object in Common Lisp: do not destructively modify it. If you need a modifiable copy, use copy-tree or construct fresh lists programmatically.

A compact, idiomatic way to generate a 5x5 rotated grid is to use nested loop forms. The following example produces the rows you described (1 2 3 4 5, then 2 3 4 5 1, etc.) for any size n:

(defun rotated-grid (n)
  (loop for r from 0 below n
        collect (loop for c from 0 below n
                      collect (1+ (mod (+ r c) n)))))

Call (rotated-grid 5) to get a 5x5 list of lists. If you prefer a purely functional approach, mapcar over a sequence of row indices to build each row; for simple fixed data, a quoted nested list is simplest. When you need to access elements later, nth (or destructuring in destructuring-bind) is more convenient than repeated car/cdr chaining.

Recommended Answers

All 2 Replies

Would something like this work?

(defun list (row-and-column (1 2 3 4 5
                             2 3 4 5 1
                             3 4 5 1 2
                             4 5 1 2 3
                             5 1 2 3 4)))

That won't work in common lisp for a number of reasons. This would, though:

(defun row-and-column ()
  '((1 2 3 4 5)
    (6 7 8 9 0)
    (1 2 3 4 5)
    (6 7 8 9 0)
    (1 2 3 4 5)))

Honestly, though, I can't figure out exactly what the OP wanted...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.