对于一个爱好项目,我处理
等a-list的列表 ((0 . 0) (0 . 1) (0 . 3) (0 . 4) (0 . 7) (0 . 8))
,列表最多可以包含9个元素,a列表仅由0
至9
之间的整数组成。我想将列表分成连续cdr
个子单元。
(((0 . 0) (0 . 1)) ((0 . 3) (0 . 4)) ((0 . 7) (0 . 8)))
一个子单元只能有一个元素,而列表根本没有子单元,例如:
((0 . 0) (0 . 1) (0 . 2) (0 . 4))
或
((0 . 0) (0 . 1) (0 . 2) (0 . 3) (0 . 4))
结果应为:
(((0 . 0) (0 . 1)) ((0 . 3) (0 . 4)) ((0 . 7) (0 . 8)))
(((0 . 0) (0 . 1) (0 . 2)) ((0 . 4)))
(((0 . 0) (0 . 1) (0 . 2) (0 . 3) (0 . 4)))
我使用iterate提出了两步式方法。首先,扫描列表并检查是否存在子单元,并返回间隙的位置。其次,使用之前实现的功能split-at
将列表分开:
(defun split-at (count original-list)
(unless (or (null original-list) (minusp count)
(>= count (length original-list)))
(list (subseq original-list 0 count)
(subseq original-list count))))
(defun sub-units (units)
"Scan UNITS for sub-units."
(iter
(for (a . b) in units)
(for last-b previous b initially -1)
(for pos from 0)
(unless (= 1 (- b last-b))
(collecting pos))))
(defun split-sub-units (units)
"Splits UNITS into its sub-units."
(iter
(with pos = (or (sub-units units) (list 0)))
(for p in pos)
(for last-p previous p)
(for (head tail) first (split-at p units) then (split-at last-p tail))
(when head
(collect head into result))
(finally (return (nconc result (list tail))))))
是否可以将两个功能sub-units
和split-sub-units
合并为一个?在样式或效率上有什么区别吗?
答案 0 :(得分:3)
我认为可以通过以下方式迭代来解决问题:收集列表中的所有元素,直到它们的cdr连续为止,然后重复之前的过程,直到原始列表为空,收集所有产生的列表。可以迭代完成此操作,总费用为 O(n),其中 n 是原始列表的长度。
我使用loop
代替iterate
,因为我对第一种构造更为熟悉,将其转换为迭代应该很简单。
(defun split (l)
(loop for (a b) = (loop for (x . y) on l
collect x into a
when (and y (/= (cdar y) (1+ (cdr x))))
do (return (list a y)) ; split here
finally (return (list a nil))) ; never split
collect a ; a list has been produced, collect it
while b ; if there are other elements
do (setf l b))) ; repeat splitting over them
一些测试:
CL-USER> (split '((0 . 0) (0 . 1) (0 . 2)))
(((0 . 0) (0 . 1) (0 . 2)))
CL-USER> (split '((0 . 0) (0 . 1) (0 . 3) (0 . 4) (0 . 7) (0 . 8)))
(((0 . 0) (0 . 1)) ((0 . 3) (0 . 4)) ((0 . 7) (0 . 8)))
CL-USER> (split '((0 . 0)))
(((0 . 0)))
CL-USER> (split '())
(NIL)