0

I have found a lot of resources on SO and books but none of them were understandable (enough) for me. I'm trying to iterate through an array with LISP.

Here is how i create my array:

(setf question-array
      (make-array '(8 2)
                  :initial-contents
                  '((1 "How old are you:")
                    (2 "Whats your name:")
                    ...)))

But after some research it looks like i should use:

(mapcar (lambda (x)
          (print))
        '(question-array))

But it only print:

QUESTION-ARRAY

I would like to print each question. So i guess #'second ? What am i missing ?

(More context: My goal is to ask questions to users and store answers somehow to count point at the end.)

Thanks a lot !

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
  • Lispers read Lisp using indentation, so you would make our (and yours!) lives much easier if you indented your code properly (as I now did). You can use Emacs to indent your code automatically. – sds Mar 13 '23 at 23:44
  • Do you insist on using a 2d array? I would use a 1d list or vector (only questions), but maybe you have some reason to include indices in your array - are they important somehow? – Martin Půda Mar 14 '23 at 08:33
  • Also, could you add more information about your specific use case? "iterate through data and print" is quite general (`loop`, `dolist`, `dotimes`,...), but "ask questions to users and store answers somehow to count point at the end" sounds more like `loop` + `collect`. – Martin Půda Mar 14 '23 at 10:06
  • An example with loop here: https://lispcookbook.github.io/cl-cookbook/iteration.html#loop-across use "across" – Ehvince Mar 14 '23 at 10:41
  • An almost-certainly-better approach would be to have a list (not array) of questions, and use `mapcar` to construct another list of answers for each question. – ignis volens Mar 16 '23 at 12:24

1 Answers1

7
  1. mapcar only works on lists, not vectors
  2. You are not passing x to print in your lambda
  3. You are quoting (question-array) so the function is not called - but it is not a function, it is a variable!

To iterate over a vector use map:

(setq question-vector (vector "question 1" "question 2" ...))
(map nil #'print question-vector)

or dotimes:

(dotimes (i (length question-vector))
  (print (aref question-vector i)))

or loop:

(loop for q across question-vector
  do (print q))

Your question-array is actually a 2-dimensional array and not a vector (so it is not a sequence, and map cannot help you).

Instead, you can do

(dotimes (i (array-dimension question-array 0))
  (print (aref question-array i 1)))
coredump
  • 37,664
  • 5
  • 43
  • 77
sds
  • 58,617
  • 29
  • 161
  • 278