RFC: mapcar with an index

Discussion of Common Lisp

RFC: mapcar with an index

Postby garethw » Thu Aug 11, 2016 7:24 am

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"?
~garethw
User avatar
garethw
 
Posts: 43
Joined: Fri Jul 13, 2012 12:56 pm
Location: Ottawa, ON

Re: RFC: mapcar with an index

Postby pjstirling » Thu Aug 11, 2016 10:05 am

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.
pjstirling
 
Posts: 140
Joined: Sun Nov 28, 2010 4:21 pm


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 1 guest

cron