This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

RFC: mapcar with an index

2 posts · 3306 views

Hi all,

From time to time, I find myself wanting to use MAPCAR where the function would like to make use of the index. I've done it in some kind of stupid ways in the past, and then came up with this:
(defun make-counter ()
  (let ((count 0))
     (lambda ()
        (prog1 count (incf count)))))

(defun make-counter-circle ()
  (alexandria:make-circular-list 1 :initial (make-counter)))

(mapcar (lambda (n x)
          (list (funcall n) x))
        (make-counter-circle)
        '(a b c d e f g))

=>  ((0 A) (1 B) (2 C) (3 D) (4 E) (5 F) (6 G))
I can't see anything obviously wrong with it, but I don't think I've seen this before.

Is this sensible? A known pattern? A world-changing work of inspired genius? "Not even wrong"?
~garethw

Re: RFC: mapcar with an index

I have a function RANGE that I tend to use for this sort of thing, but yes, there's not a totally convenient way to do this built into Common-Lisp.