有时我需要遍历列表中的连续对.我现在这样做的方式是
(loop for x on lst while (not (null (cdr x)))
(do something on (car x) and (cadr x)))
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好/内置的方法来做到这一点.
我需要这个的原因有时是我想要的,例如一些添加连续对的函数
(1 2 3 4 5) ----> (3 5 7 9)
Run Code Online (Sandbox Code Playgroud)
是否有像reduce这样的内置函数可以让我得到这个?
AFAIK,没有内置功能可以做你想要的.你可以试着把东西放在一起maplist
,但我的第一直觉就是伸手loop
去拿.
关于你在那里得到的东西只是几个笔记.首先,(not (null foo))
等同foo
于CL,因为非NIL
值被视为t
布尔运算.其次,loop
可以解构其论点,这意味着你可以更优雅地写出来
(loop for (a b) on lst while b
collect (+ a b))
Run Code Online (Sandbox Code Playgroud)
该maplist
版本看起来像
(maplist
(lambda (rest)
(when (cdr rest)
(+ (first rest) (second rest)))
lst)
Run Code Online (Sandbox Code Playgroud)
我认为它的可读性较低(这也会将NIL作为其结果的最后一个元素返回,而不是在此之前结束).
归档时间: |
|
查看次数: |
2521 次 |
最近记录: |