Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I loop with more than 1 variable at once in Common Lisp?

So, I can loop with one variable like this:

(loop for i in ‘(1 2 3 4 5) do (print i))

I can get 1 number and bind it to i.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But how can I bind to more than 1 variable at once, e.g. something like for i,j,k in '(1 2 3 4 5) -> i = 1, j = 2, k = 3

I already tried searching around but only found with statement to define more variables, but it does not allow me to bind the variables directly.

>Solution :

You can bind multiple variables simultaneously in a loop by using a sublist for each variable. Here’s an example of how you can achieve it:

(loop for (i j k) in '((1 2 3) (4 5 6) (7 8 9))
      do (print (list i j k)))

The loop iterates over a list of lists, and each inner list contains three elements. The variables (i, j, k) get bound to the elements of each inner list. Then, within the loop body, you can perform any desired operations using these variables.

When executed, the above code will print:

(1 2 3)
(4 5 6)
(7 8 9)

EDIT: The OP is looking for a result that involves only one list. This is also achievable in Common Lisp:

(loop for (i j k) on '(1 2 3 4 5 6 7 8 9)
      by #'cddr
      while k
      do (print (list i j k)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading