升序中的连续子列表 [英] contiguous sublists from an ascending sequence

查看:102
本文介绍了升序中的连续子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给予

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建议中返回了以下内容页面

a little bit of searching returned the following from the Haskell Data.List suggestion 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)

他们给出的例子之一就是我所寻找的:

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]]

所以我的问题...是否还有另一种方法,而不是像重新定义groupBy那样看起来有些戏剧性?

So My question... Is there another approach to this, as opposed to re-defining groupBy as it seems a little dramatic?

编辑...

我决定按以下方式实施它:

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

可以进行以下操作:

*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一样起作用-并不是有任何原因:

or to function exactly like group -- not that there is any reason:

*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

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]]

这篇关于升序中的连续子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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