[Haskell-beginners] Better Code
joel.neely at gmail.com
Fri Jan 13 17:40:57 UTC 2017
The "helper list" technique is ingenious, but seems very specific to Int as
the type within the list.
I have had other tasks that seem to fit a more generalized problem
statement, of which the original question appears to me as special case:
Given a criterion of type a -> a -> Bool and a list [a], produce a list of
lists [[a]] in which sub-lists are made up of consecutive elements from the
original list that satisfy the criterion.
It appears to me that List.groupBy may meet that need, but I'm not able to
verify that at the moment (and would be glad of feedback).
On Fri, Jan 13, 2017 at 10:55 AM, Francesco Ariis <fa-ml at ariis.it> wrote:
> 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
> > 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)
> 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
> and now grouped by using `groupBy` in Data.List.
> Does that help?
> Beginners mailing list
> Beginners at haskell.org
Beauty of style and harmony and grace and good rhythm depend on simplicity.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners