Search code examples
lispcommon-lispnested-loopssequential

LISP nested Loops perform in parallel. How would one force it to perform sequentially?


I have been slowly learning Lisp over the past 2 weeks. I have come across a situation where Lisp performs two Loops in parallel, and is not what I am aiming for. If I understand correctly, what I want to achieve would be categorized as sequentially. To give you an idea of what happens, we can take a look at the following:

(loop for x in '(a b c d e)
      for y in '(1 2 3 4 5)
        collect (list x y))

With this type of coding, one will get:

((A 1) (B 2) (C 3) (D 4) (E 5))

But what I am seeking is:

((A 1) (A 2) (A 3) (A 4) (A 5) (B 1) (B 2) (B 3) and so on

What would I need to change with the Loop to get this type of desired result? If I am wrong in the usage of the term "sequentially", please correct me. I have been reading up on it, but I am having a bit of a hard time grasping this.


Solution

  • You need nested loops:

    (loop for x in '(a b c d e)
          nconc (loop for y in '(1 2 3 4 5)
                      collect (list x y)))