给定的
xs = [1,2,3,4,6,7,9,10,11]
我的目标是返回
[[1,2,3,4],[6,7],[9,10,11]]
我以为我能做到:
groupBy (\x y -> succ x == y) xs
但这会返回:
[[1,2],[3,4],[6,7],[9,10],[11]]
一点点搜索从Haskell Data.List建议page返回以下内容。
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy rel [] = []
groupBy rel (x:xs) = (x:ys) : groupBy rel zs
where (ys,zs) = groupByAux x xs
groupByAux x0 (x:xs) | rel x0 x = (x:ys, zs)
where (ys,zs) = groupByAux x xs
groupByAux y xs = ([], xs)
他们给出的一个例子就是我正在寻找的东西:
groupBy (\a b -> a+1 == b) [1,2,3,4,6]
[[1,2,3,4],[6]]
所以我的问题......是否有另一种方法,而不是重新定义groupBy
,因为它似乎有点戏剧性?
编辑......
我决定按如下方式实施:
pattern :: (Enum a, Eq a) => (a -> a) -> [a] -> [[a]]
pattern f = foldr g []
where g a [] = [[a]]
g a xs | f a == head (head xs) = (a : head xs): tail xs
| otherwise = [a]:xs
允许这样的事情:
*Main Map> pattern succ "thisabcdeisxyz"
["t","hi","s","abcde","i","s","xyz"]
*Main Map> pattern (+ 3) [3,6,9,12,1,2,3,2,5,8,23,24,25]
[[3,6,9,12],[1],[2],[3],[2,5,8],[23],[24],[25]]
或与group
完全相同的功能 - 并非有任何理由:
*Main Map> let xs = [1,1,1,2,3,4,5,6,6,6,5]
*Main Map> group xs == pattern id xs
True
答案 0 :(得分:5)
有很多方法可以做到这一点。一种方法可以使用foldr
f = foldr g []
where g a [] = [[a]]
g a xs@(x:xs') | a+1 == head x = (a : x): xs'
| otherwise = [a]:xs
现在尝试执行此操作
*Main> f [1,2,3,4,6,7,9,10,11]
[[1,2,3,4],[6,7],[9,10,11]]
答案 1 :(得分:3)
如果xs
严格增加,那么
myGrouping = map (map snd) . groupBy (\(u, v) (x, y) -> u - v == x - y) . zip [0..]
解决您的问题。
Prelude> myGrouping [1,2,3,4,6,7,9,10,11]
[[1,2,3,4],[6,7],[9,10,11]]