2014-07-20 29 views
0

當給出Set實例而不是List實例時,for循環的行爲會如何更改?迭代Set而不是List時的for循環行爲

小提琴:http://scalafiddle.net/console/67ed94744426295f96268f4ac1881b46

代碼:

case class Book(title: String, authors: List[String]) {} 

val books = List(
    Book("Book 1", List("Author 1", "Author 2")), 
    Book("Book 2", List("Author 2")), 
    Book("Book 3", List("Author 3")), 
    Book("Book 4", List("Author 4")) 
) 

def authorsWithMultipleBooks(books: Iterable[Book]) = 
    for { 
    b1 <- books 
    b2 <- books 
    if b1 != b2 
    a1 <- b1.authors 
    a2 <- b2.authors 
    if a1 == a2 
    } yield a1 

println(authorsWithMultipleBooks(books)) 
// Output: List(Author 2, Author 2) 
println(authorsWithMultipleBooks(books.toSet)) 
// Output: Set(Author 2) 

回答

3

在你屈服"Author 2"兩次這兩種情況下,但由於Set僅持有每個元素的一個istance,你得到它的第二次它不會改變集合。

因此,for循環的行爲不會改變,唯一不同的作用是在結果集合中插入,其中 - 作爲集合 - 放棄重複插入。

下面是一個例子,進一步明確思路:

scala> val authors = List("Author 1", "Author 2", "Author 3") 
authors: List[String] = List(Author 1, Author 2, Author 3) 

scala> for { 
    | _ <- authors 
    | } yield "Author 2" 
res8: List[String] = List(Author 2, Author 2, Author 2) 

scala> val authorsSet = authors.toSet 
authorsSet: scala.collection.immutable.Set[String] = Set(Author 1, Author 2, Author 3) 

scala> for { 
    | _ <- authorsSet 
    | } yield "Author 2" 
res10: scala.collection.immutable.Set[String] = Set(Author 2) 
+0

很好的解釋!謝謝 –