成组排序的整数列表的惯用方式? [英] Idiomatic way to group a sorted list of integers?

查看:59
本文介绍了成组排序的整数列表的惯用方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序的整数列表,(1 2 4 5 6 6 7 8 10 10 10).我想将它们全部分组,以便得到((1) (2) (4) (5) (6 6) (7) (8) (10 10 10)).

I have a sorted list of integers, (1 2 4 5 6 6 7 8 10 10 10). I want to group them all, so that I get ((1) (2) (4) (5) (6 6) (7) (8) (10 10 10)).

到目前为止,我有这个,它可以工作:

So far I have this, which works:

(let ((current-group (list)) (groups (list)))
  (dolist (n *sorted*)
    (when (and (not (null current-group)) (not (eql (first current-group) n)))
      (push current-group groups)
      (setf current-group (list)))
    (push n current-group))
  (push current-group groups)
  (nreverse groups))

但是我敢肯定,必须有更多的LISPy方法来做到这一点.有什么想法吗?

But I'm sure there must be a much more LISPy way to do this. Any ideas?

推荐答案

还不错.我会这样写:

(defun group (list)
  (flet ((take-same (item)
           (loop while (and list (eql (first list) item))
                 collect (pop list))))
    (loop while list
          collect (take-same (first list)))))


CL-USER 1 > (group '(1 2 4 5 6 6 7 8 10 10 10))
((1) (2) (4) (5) (6 6) (7) (8) (10 10 10))

这篇关于成组排序的整数列表的惯用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆