Page 1 of 1

RFC: mapcar with an index

Posted: Thu Aug 11, 2016 7:24 am
by garethw
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:

Code: Select all

(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"?

Re: RFC: mapcar with an index

Posted: Thu Aug 11, 2016 10:05 am
by pjstirling
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.