title: Scala: groupBy (identity) of List Elements
body: <p>I develop an application that builds pairs of words in (tokenised) text and produces the number of times each pair occurs (even when same-word pairs occur multiple times, it's OK as it'll be evened out later in the algorithm).</p>
  
  <p>When I use</p>
  
  <pre><code>elements groupBy()
  </code></pre>
  
  <p>I want to group by the elements' content itself, so I wrote the following:</p>
  
  <pre><code>def self(x: (String, String)) = x
  
  /**
   * Maps a collection of words to a map where key is a pair of words and the 
   *  value is number of
   * times this pair
   * occurs in the passed array
   */
  def producePairs(words: Array[String]): Map[(String,String), Double] = {
    var table = List[(String, String)]()
    words.foreach(w1 =&gt;
      words.foreach(w2 =&gt;
        table = table ::: List((w1, w2))))
  
  
    val grouppedPairs = table.groupBy(self)
    val size = int2double(grouppedPairs.size)
    return grouppedPairs.mapValues(_.length / size)
  }
  </code></pre>
  
  <p>Now, I fully realise that this self() trick is a dirty hack. So I thought a little a came out with a:</p>
  
  <pre><code>grouppedPairs = table groupBy (x =&gt; x)
  </code></pre>
  
  <p>This way it produced what I want. However, I still feel that I clearly miss something and there should be easier way of doing it. Any ideas at all, dear all?</p>
  
  <p>Also, if you'd help me to improve the pairs extraction part, it'll also help a lot – it looks very imperative, C++ - ish right now. Many thanks in advance!</p>