2

I want to iterate over a list with both the index and the value in the loop.

Currently, the code looks like this:

(let ((my-list '(a b c)))
  (cl-loop for index below (length my-list)
           for item = (seq-elt my-list index)
           do (insert (format "index=%s, item=%s\n" index item))))

but calling seq-elt each time is not reasonable.

Another solution looks like this:

(let ((my-list '(a b c)))
  (cl-loop for item being the elements of my-list using (index index)
           do (insert (format "index=%s, item=%s\n" index item))))

But the documentation seems to indicate its obsolete (at least in Common Lisp).

I can't use seq-do-indexed because it was introduced after Emacs 25 with which I would like to keep backward compatibility until 27 is released.

Here is a home-made version that works, but I would prefer a builtin solution if one exists:

(let ((my-list '(a b c))
      (index 0))
  (dolist (item my-list)
    (insert (format "index=%s, item=%s\n" index item))
    (cl-incf index)))

Here is the actual code I'm not satisfied with.

Damien Cassou
  • 877
  • 4
  • 14
  • 1
    Good question. IMHO, your "homemade version" is clearer and lispier than all of the `cl-loop` versions. Simple, short, obvious. No need to know another language: ["the loop facility"](https://www.gnu.org/software/emacs/manual/html_node/cl/Loop-Facility.html#Loop-Facility). (Just one opinion.) – Drew Aug 21 '19 at 15:19

1 Answers1

8

This is actually not really different from your "home-made" version, but uses a loop clause to handle the incrementing:

(let ((my-list '(a b c)))
  (cl-loop for index from 0
           for item in my-list
           do (insert (format "index=%s, item=%s\n" index item))))
npostavs
  • 9,033
  • 1
  • 21
  • 53