toy list processing problem: collect similar terms

Ertugrul Söylemez es at
Mon Sep 27 01:41:37 CEST 2010

Xah Lee <xahlee at> wrote:

> here's a interesting toy list processing problem.
> I have a list of lists, where each sublist is labelled by a number. I
> need to collect together the contents of all sublists sharing the same
> label. So if I have the list
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
> where the first element of each sublist is the label, I need to
> produce:
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> [...]
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.

In Haskell the solution looks like this:

  import qualified Data.Map as M
  import qualified Data.Set as S
  import Data.Map (Map)
  import Data.Set (Set)

  collect :: (Ord a, Ord k) => [Map k (Set a)] -> Map k (Set a)
  collect = M.unionsWith S.union


nightmare = unsafePerformIO (getWrongWife >>= sex)

More information about the Python-list mailing list