Sometimes I need to loop through consecutive pairs in a list. The way I do it right now is
(loop for x on lst while (not (null (cdr x)))
(do something on (car x) and (cadr x)))
I'm wondering if there is a better/built-in way to do this.
The reason I need this is sometimes I want, e.g. some function that add consecutive pairs
(1 2 3 4 5) ----> (3 5 7 9)
Is there any built-in function like reduce which allow me to get this?
I believe Paul Graham has a function named map-tuple in OnLisp which does this. It can move down the list by cdr, cddr, or however you please. Here is a commented version of it. It uses his anaphoric if macro aif.
AFAIK, there isn't a built-in function to do what you want. You could try to put something together with
maplist
, but my first instinct would be to reach forloop
too.Just a couple of notes on what you've got there though. First,
(not (null foo))
is equivalent tofoo
in CL, since a non-NIL
value is treated ast
by boolean operations. Second,loop
can destructure its arguments, meaning you can write this more elegantly asThe
maplist
version would look something likewhich I consider less readable (this would also return NIL as the last element of its result, rather than just ending before that).