2016-05-24 2 views
0

Ich bin neu für Scala. Ich habe eine Frage zu der Reihenfolge in der Foor-Schleife.Hat die Reihenfolge in Scala für Schleife Einfluss

type Occurrences = List[(Char, Int)] 

lazy val dictionaryByOccurrences: Map[Occurrences, List[Word]] = dictionary.groupBy(x => wordOccurrences(x)) 

def wordAnagrams(word: Word): List[Word] = dictionaryByOccurrences.getOrElse(wordOccurrences(word), List()) 

def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match { 
    case List() => List(List()) 
    case head::tail => { 
    for (o <- combinations(tail); x <- 1 to head._2) 
    yield (head._1, x) :: o 
} 

wenn ich die Reihenfolge, in der for-Schleife ändern, wird es

def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match { 
    case List() => List(List()) 
    case head::tail => { 
    for (x <- 1 to head._2; o <- combinations(tail)) 
    yield (head._1, x) :: o 
} 

falsch sein Ich kann nicht der Grund

Antwort

1

Der Typkonstruktor von for(x <- xs; y <- ys; ...) yield f(x, y, ...) ist das gleiche von xs standardmäßig finden . Nun ist der Rückgabetyp combinationsList[Occurrences], dann ist der erwartete Typkonstruktor List[_], während der Typenkonstruktor 1 to nSeq[_] ist.

Die folgenden Codes funktionieren:

def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match { 
    case List() => List(List()) 
    case head::tail => { 
    for (x <- (1 to head._2).toList; o <- combinations(tail)) 
    yield (head._1, x) :: o 
} 

Und das auch funktionieren würde:

import collection.breakOut 
def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match { 
    case List() => List(List()) 
    case head::tail => { 
     (for (x <- 1 to head._2; o <- combinations(tail)) 
     yield (head._1, x) :: o)(breakOut) 
    } 
} 

In der Tiefe ist for(x <- xs; y <- ys; ...) yield f(...) entspricht xs.flatMap(...) und die volle Unterschrift List#flatMap, wie folgend:

def flatMap[B, That](f: (A) ⇒ GenTraversableOnce[B]) 
        (implicit bf: CanBuildFrom[List[A], B, That]): That 

Sie können sehen, dass die r Typ flatMap ist ein MagieThat die List[B] standardmäßig ist, können Sie in Scala 2.8 CanBuildFrom für weitere Informationen suchen.

Verwandte Themen