在Lisp中一次处理列表中的n个项目

编程入门 行业动态 更新时间:2024-10-24 18:19:42
本文介绍了在Lisp中一次处理列表中的n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出一个列表,我如何一次处理 N 个项目? Ruby each_slice 方法;什么是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个项目

本文发布于:2023-11-28 22:44:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644242.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   列表中   Lisp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!