title: for comprehension on Lists/Sets in scala
body: <p>This is possibly a naive question. I have a case class 'Book', defined below:</p>
  
  <pre><code>case class Book(title : String, authors : List[String])
  </code></pre>
  
  <p>In my main method, I define a few Book records as follows:</p>
  
  <pre><code>val books = List(
    Book(title = "Book1", authors = List("Author1", "Author2")),
    Book(title = "Book2", authors = List("Author3", "Author4")),
    Book(title = "Book3", authors = List("Author2", "Author5")),
    Book(title = "Book4", authors = List("Author6", "Author3")),
    Book(title = "Book5", authors = List("Author7", "Author8")),
    Book(title = "Book6", authors = List("Author5", "Author9"))
  )
  </code></pre>
  
  <p>I am writing a query to retrieve the names of authors who have authored more than one book, and my query is as below:</p>
  
  <pre><code>val authorsWithMoreThanTwoBooks =
        (for {
  
          b1 &lt;- books
          b2 &lt;- books
          if b1.title != b2.title
          a1 &lt;- b1.authors
          a2 &lt;- b2.authors
          if a1 == a2
        } yield a1)
  
  println(authorsWithMoreThanTwoBooks)
  </code></pre>
  
  <p>This prints <code>List(Author2, Author3, Author2, Author5, Author3, Author5)</code> (the name of the authors appearing twice which is quite expected, since every pair of books will be taken twice, like (b1,b2) and (b2,b1)).</p>
  
  <p>Of course I could use <code>distinct</code> to solve this problem , but another way is to create the records not in a List but in a <strong>Set</strong> :</p>
  
  <pre><code>val books = Set(
    Book(title = "Book1", authors = List("Author1", "Author2")),
    Book(title = "Book2", authors = List("Author3", "Author4")),
    Book(title = "Book3", authors = List("Author2", "Author5")),
    Book(title = "Book4", authors = List("Author6", "Author3")),
    Book(title = "Book5", authors = List("Author7", "Author8")),
    Book(title = "Book6", authors = List("Author5", "Author9"))
  )
  </code></pre>
  
  <p>Output after <code>for</code> expression and <code>println</code>: <code>Set(Author5, Author2, Author3)</code></p>
  
  <p>Why does this behavior happen? Why does the <code>for</code> expression on <code>Set</code> generate another <code>Set</code> and not a <code>List</code>? Is it possible to get a <code>List</code> of the relevant authors with the duplicate values if ever required?</p>