[Haskell-beginners] Better Code
Carlo Matteo Scalzo
cmscalzo at gmail.com
Fri Jan 13 22:43:27 UTC 2017
perhaps something like this?
divide :: [Int] -> [[Int]]
divide  = 
divide (x:xs) = divideAux xs  [x] x
divideAux :: [Int] -> [[Int]] -> [Int] -> Int -> [[Int]]
divideAux  result current max = result ++ [current]
divideAux (x:xs) result current max = if x - max > 1
divideAux xs (result ++ [current]) [x] x
divideAux xs result (current ++ [x]) x
This can of course be generalised to other types (as per Joel's
requirement) just by replacing the check on line 7, i.e., 'x - max > 1'.
Happy to explain/talk about the code if you'd like me to :-)
On Fri, Jan 13, 2017 at 7:14 PM, Joel Neely <joel.neely at gmail.com> wrote:
> Had a chance to chat with ghci, so earlier conjecture not confirmed:
> Prelude Data.List> groupBy (\x y -> x == y-1) [1,2,3,7,8,10,11,12]
> So close but no cigar.
> On Fri, Jan 13, 2017 at 10:05 AM, Saqib Shamsi <shamsi.saqib at gmail.com>
>> 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
>> 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
>> divide :: [Int] -> [Int] -> ([Int], [Int])
>> divide first  = (first, )
>> divide first second = if (last first) /= firstSecond - 1 then (first,
>> 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 
>> firstElem = head lst
>> remaining = tail lst
>> (one, two) = divide [firstElem]
>> -- 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
>> Beginners mailing list
>> Beginners at haskell.org
> Beauty of style and harmony and grace and good rhythm depend on
> simplicity. - Plato
> Beginners mailing list
> Beginners at haskell.org
Carlo Matteo Scalzo
Mobile: +44 (0) 7934 583582
E-mail: cmscalzo at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners