[Haskell-beginners] Better Code

Francesco Ariis fa-ml at ariis.it
Fri Jan 13 16:55:16 UTC 2017


On Fri, Jan 13, 2017 at 09:35:54PM +0530, Saqib Shamsi wrote:
> The problem that I wish to solve is to divide a (sored) list of integers
> into sublists such that each sublist contains numbers in consecutive
> sequence.
> 
> For example,
> *Input:* [1,2,3,7,8,10,11,12]
> *Output:* [[1,2,3],[7,8],[10,11,12]]
> 
> [...]
> 
> However, I was wondering if there was a better way of doing this. Any help
> would be highly appreciated.

Hello Saquib,
    you could try using a 'trick' like this:

λ> zipWith (-) [1,2,3,7,8,10,11,12] (enumFrom 1)
[0,0,0,3,3,4,4,4]

Now you have an 'helper' list which can be glued to the first one
with zip

λ> zip [1,2,3,7,8,10,11,12] it
[(1,0),(2,0),(3,0),(7,3),(8,3),(10,4),(11,4),(12,4)]

and now grouped by using `groupBy` in Data.List.

Does that help?


More information about the Beginners mailing list