2

Suppose that i have a list in this format=

$list=\{ \{a,obj1 \} ,\{c,obj2 \}, \{a,obj3 \}, \{b,obj4 \} \dots\}$

I want to construct a new list in this way:

$ newlist= \{ \{ \{a,obj1\} , \{a,obj3\} ... \}, \{ \{b,obj4\} , \{b,obj5\} ... \} ...\} $

This is, the new list must have sublist in which the first element of each sub-element is the same. In this way we have that for example, the first element of $newlist$ is formed by all the pairs in the form $\{a, [] \}$, the second element is formed by all the pairs in the form $\{b, [] \}$ ...etc.

My current approach is the following:

  • Use $elements=Union[list[[All,1]] ]$ to get all different first-elements.
  • Use $Select$ to get all elements of $list$ that has the same first-element extracted from $elements$.
  • Construct a new list combining the two points.

What I whant is a "clever" functional-programming way to achieve this using the fewest functions possible.

I believe that this is an interesting question for people that are learning functional-programming (as me, for example).

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Dargor
  • 1,369
  • 9
  • 17
  • This question is a simplistic version of: (4332) – Mr.Wizard Mar 03 '15 at 23:15
  • Yeah @Mr.Wizard, and it turns it is not as interesting as I thought so as i said in other comment: Sorry for the is-in-the-help-question. :( (Also, i tried to find another similar question but the use of "columns" in the other question made my search not as productive as i wanted to....sorry again). – Dargor Mar 03 '15 at 23:27
  • It is okay. Thank you for searching before posting. FYI: my comment above was not intended to denigrate your question but only to help you or others find related questions. :-) – Mr.Wizard Mar 03 '15 at 23:52

1 Answers1

3

GatherBy does exactly what you want.

l = {{a, obj1}, {c, obj2}, {a, obj3}, {b, obj4}};
GatherBy[l, First]

{{{a, obj1}, {a, obj3}}, {{c, obj2}}, {{b, obj4}}}

paw
  • 5,650
  • 23
  • 31
  • Wow! Thank you so much. Sometimes is hard to search within the help and not get lost. Sorry for the is-in-the-help-question. – Dargor Mar 03 '15 at 22:50