我写了一个似乎工作正常的函数。(再想一想,它错过了前两组的联系……我得再考虑一下。)
import Data.List (groupBy)
makeGroups xs =
map concat $ groupBy (\a b -> head b == last a + 1) (groupBy mGroups0 xs)
where mGroups0 = \a b -> a == length xs && elem b [1,2]
|| b /= length xs && b == a + 1
输出:
*Main> makeGroups [3,4,5,6,7,8,1,9,10,2]
[[3,4,5,6],[7,8],[1],[9,10,2]]
(谢谢大家对标签的回答......现在我只要求一般的编码天才)
是否有更有效/更方便的方法将排序的升序整数序列分组到列表中(保持原始顺序)?
唯一的额外规定是:
the possible groups [length xs] [1] [2] [1,2] [length xs,1] [length xs,2]
must be separated, but [length xs, 1, 2] should join any larger sequence.