Re: [Haskell-beginners] Beginners Digest, Vol 103, Issue 8

Hello Francesco,
Sorry for the late reply. Yes, your solution is elegant and does what I
wanted. This is what I did
-- zipped is the list of tuples formed as you mentioned
λ> groupBy (\x y -> (snd x) == (snd y)) zipped
[[(1,0),(2,0),(3,0)],[(7,3),(8,3)],[(10,4),(11,4),(12,4)]]
λ> [[fst tpl | tpl <- x] | x <- it]
[[1,2,3],[7,8],[10,11,12]]
This works perfectly fine.
Thank you.
Regards,
Saqib Shamsi
On 14 January 2017 at 00:27,
Send Beginners mailing list submissions to beginners@haskell.org
To subscribe or unsubscribe via the World Wide Web, visit http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners or, via email, send a message with subject or body 'help' to beginners-request@haskell.org
You can reach the person managing the list at beginners-owner@haskell.org
When replying, please edit your Subject line so it is more specific than "Re: Contents of Beginners digest..."
Today's Topics:
1. Better Code (Saqib Shamsi) 2. Re: Better Code (Francesco Ariis) 3. Re: Better Code (Joel Neely) 4. Re: Better Code (Joel Neely)
----------------------------------------------------------------------
Message: 1 Date: Fri, 13 Jan 2017 21:35:54 +0530 From: Saqib Shamsi
To: beginners@haskell.org Subject: [Haskell-beginners] Better Code Message-ID: Content-Type: text/plain; charset="utf-8" Hi,
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]]
I have written the following code and it does the trick.
-- Take a list and divide it at first point of non-consecutive number encounter divide :: [Int] -> [Int] -> ([Int], [Int]) divide first [] = (first, []) divide first second = if (last first) /= firstSecond - 1 then (first, second) else divide (first ++ [firstSecond]) (tail second) where firstSecond = head second
-- Helper for breaking a list of numbers into consecutive sublists breakIntoConsecsHelper :: [Int] -> [[Int]] -> [[Int]] breakIntoConsecsHelper [] [[]] = [[]] breakIntoConsecsHelper lst ans = if two == [] then ans ++ [one] else ans ++ [one] ++ breakIntoConsecsHelper two [] where firstElem = head lst remaining = tail lst (one, two) = divide [firstElem] remaining
-- Break the list into sublists of consective numbers breakIntoConsecs :: [Int] -> [[Int]] breakIntoConsecs lst = breakIntoConsecsHelper lst [[]]
-- Take the tail of the result given by the function above to get the required list of lists.
However, I was wondering if there was a better way of doing this. Any help would be highly appreciated.
Thank you. Best Regards, Saqib Shamsi
participants (1)
-
Saqib Shamsi