Common Lisp:在列表中的连续对之间循环的最佳方法是什么? [英] Common Lisp: what's the best way to loop through consecutive pairs in a list?
问题描述
有时我需要遍历列表中的连续对。我现在的操作方式是
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)))
我是
我有时需要这样的原因,例如,我想知道是否有更好的/内置的方法来做到这一点。一些添加连续对的函数
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)
是否有任何内置函数(如reduce)可以让我得到?
Is there any built-in function like reduce which allow me to get this?
推荐答案
AFAIK,没有内置函数可以执行您想要的操作。您可以尝试将某些内容与 maplist
组合在一起,但是我的第一个直觉是也可以达到 loop
。
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 for loop
too.
不过,您只需要注意几个便笺即可。首先,(not(null foo))
等效于CL中的 foo
,因为非<$ c $布尔运算将c> NIL 的值视为 t
。其次, loop
可以分解其参数,这意味着您可以更优雅地编写为
Just a couple of notes on what you've got there though. First, (not (null foo))
is equivalent to foo
in CL, since a non-NIL
value is treated as t
by boolean operations. Second, loop
can destructure its arguments, meaning you can write this more elegantly as
(loop for (a b) on lst while b
collect (+ a b))
地图列表
版本看起来像
(maplist
(lambda (rest)
(when (cdr rest)
(+ (first rest) (second rest)))
lst)
我认为它的可读性较差(这还将返回NIL作为结果的最后一个元素,而不是仅仅在此之前结束)。
which I consider less readable (this would also return NIL as the last element of its result, rather than just ending before that).
这篇关于Common Lisp:在列表中的连续对之间循环的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!