给定
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 建议页面返回以下内容。
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