在Lisp中一次处理列表中的n个项目 [英] Process n items from a list at a time in Lisp
问题描述
给出一个列表,我如何一次处理 N 个项目? Ruby each_slice
Enumerable 上的> 方法;什么是Lisp等效项?
Given a list, how do I process N items at a time? Ruby has each_slice
method on the Enumerable
that does this; what would be the Lisp equivalent?
推荐答案
常见Lisp的 loop
可以很好地用于此,如以下两个示例所示。第一个示例在列表中循环(x y z)
。但是,默认步骤为 cdr
( rest
),因此如果列表为(1 2 3 4 5)
,您将得到(1 2 3)
,(2 3 4)
等,用于(xyz)
。
Common Lisp's loop
can be used for this very nicely, as in the following two examples. The first example loops for (x y z)
in a list. However, the default step is cdr
(rest
), so if the list is (1 2 3 4 5)
, you get (1 2 3)
, (2 3 4)
, etc., for (x y z)
.
CL-USER> (loop for (x y z) on '(1 2 3 4 5 6 7 8 9 10 11 12)
do (print (list z y x)))
(3 2 1)
(4 3 2)
(5 4 3)
(6 5 4)
(7 6 5)
(8 7 6)
(9 8 7)
(10 9 8)
(11 10 9)
(12 11 10)
(NIL 12 11)
(NIL NIL 12)
NIL
如果您不希望迭代之间有重叠,请将步进函数指定为可移动的东西在列表的下方。例如,如果一次要拉三个元素,请使用 cdddr
:
If you do not want the overlap between iterations, specify the stepping function to be something that moves farther down the list. For instance, if you're pulling three elements at a time, use cdddr
:
CL-USER> (loop for (x y z) on '(1 2 3 4 5 6 7 8 9 10 11 12) by 'cdddr
do (print (list z y x)))
(3 2 1)
(6 5 4)
(9 8 7)
(12 11 10)
NIL
使用这种技术实现分区
另一个答案使用 each_slice
实现了对等辅助功能。但是,请注意,分区
(在这种意义上)只是具有身份功能的 each_slice
。这表明我们应该能够使用上面的习惯用法来实现它。匿名函数
Implementing partition with this technique
Another answer implemented the counterpart to each_slice
using an auxiliary function. However, notice that partition
(in that sense) is just each_slice
with the identity function. This suggests that we should be able to implement it using the idiom above. The anonymous function
(lambda (list)
(nthcdr n list))
是我们需要的步进函数。由于我们直到运行时才知道单元格中有多少个元素,因此无法像上面那样使用(x y z)
绑定每个元素。当我们下移并提取子序列 n 元素时,我们必须匹配列表的每个尾部。这是分区
的基于循环
的实现。
is the step function that we need. Since we do not know how many elements the cells have until run time, we can't bind each element like we did above with (x y z)
. We do have to match each tail of the list as we step down and extract the subsequence n elements. Here's a loop
based implementation of partition
.
CL-USER> (defun partition (list cell-size)
(loop for cell on list by #'(lambda (list)
(nthcdr cell-size list))
collecting (subseq cell 0 cell-size)))
PARTITION
CL-USER> (partition '(1 2 3 4 5 6) 2)
((1 2) (3 4) (5 6))
这篇关于在Lisp中一次处理列表中的n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!