[Haskell-beginners] Re: Problem "grouping" a list

Hein Hundal hundalhh at yahoo.com
Thu Nov 25 10:02:44 EST 2010

> From: Jo?o Paulo Pizani Flor <joaopizani at gmail.com>
> OK, so my specific problem goes like this: I have a list of
> tuples
> :t  myList
> [ (Float, Integer) ]
> And I want to "group" this list into a nested list
> groupAtoms :: [ (Float,Integer) ]  ->  [
> [(Float,Integer)] ]
> Of course, I want that the concatenation of the groups
> yield me the original
> list, i.e,  (foldl (++) [] . groupAtoms == id), and
> the criterion that
> defines a group is that:
> "The sum of the first elements in the tuples comprising the
> list must be
> greater than or equal to 1.0". 

   I am a beginner also and I liked Daniel Fischer's solution.  Here is another (less elegant) solution:

-- Start Code Here

-- foldfun takes an existing list of lists of pairs and decides
-- whether to append p to the current list, pl, or start a new 
-- list of pairs. 

foldfun done p (pl:pls) = if done pl then [p]:pl:pls else (p:pl):pls
foldfun done p [] = [[p]] 

-- mygroup2 folds list of pairs, pl, using the foldfun, and then 
-- puts all the lists in the correct order using reverse twice.

mygroup2 pl = map reverse $ reverse $ 
                  foldr (foldfun done) [] (reverse pl)  
  where done pl = sum (map fst pl) >= 1.0

-- End of Code



More information about the Beginners mailing list