[英]contiguous sublists from an ascending sequence
given 特定
xs = [1,2,3,4,6,7,9,10,11]
I am aiming to return 我的目标是回归
[[1,2,3,4],[6,7],[9,10,11]]
I thought I could do: 我以为我能做到:
groupBy (\\xy -> succ x == y) xs
but this returns: 但是这会返回:
[[1,2],[3,4],[6,7],[9,10],[11]]
a little bit of searching returned the following from the Haskell Data.List suggestion page . 一点点搜索从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)
One of the examples they give is exacly what I am looking for: 他们给出的一个例子就是我正在寻找的东西:
groupBy (\a b -> a+1 == b) [1,2,3,4,6]
[[1,2,3,4],[6]]
So My question... Is there another approach to this, as opposed to re-defining groupBy
as it seems a little dramatic? 所以我的问题......是否有另一种方法,而不是重新定义
groupBy
因为它似乎有点戏剧性?
EDIT... 编辑...
I have decided to implement it as follows: 我决定按如下方式实施:
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
which allows for such things: 这允许这样的事情:
*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]]
or to function exactly like group
-- not that there is any reason: 或者完全像
group
一样运作 - 不是有任何理由:
*Main Map> let xs = [1,1,1,2,3,4,5,6,6,6,5]
*Main Map> group xs == pattern id xs
True
There are many ways to do that. 有很多方法可以做到这一点。 One way can be using foldr
一种方法可以使用foldr
f = foldr g []
where g a [] = [[a]]
g a xs@(x:xs') | a+1 == head x = (a : x): xs'
| otherwise = [a]:xs
Now trying this in action 现在尝试这个行动
*Main> f [1,2,3,4,6,7,9,10,11]
[[1,2,3,4],[6,7],[9,10,11]]
If xs
is strictly increasing then 如果
xs
严格增加那么
myGrouping = map (map snd) . groupBy (\(u, v) (x, y) -> u - v == x - y) . zip [0..]
solve your problem. 解决你的问题。
Prelude> myGrouping [1,2,3,4,6,7,9,10,11]
[[1,2,3,4],[6,7],[9,10,11]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.