【问题标题】:Does the order in Scala for loop influenceScala中的顺序是否影响循环
【发布时间】:2016-05-24 08:22:24
【问题描述】:

我是 Scala 的新手。我对 foo 循环中的顺序有疑问。

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
}

如果我在for循环中改变顺序,那就错了

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
}

找不到原因

【问题讨论】:

    标签: scala


    【解决方案1】:

    for(x &lt;- xs; y &lt;- ys; ...) yield f(x, y, ...) 的类型构造函数默认与xs 相同。现在combinations的返回类型是List[Occurrences],那么期望的类型构造函数是List[_],而1 to n的类型构造函数是Seq[_]

    以下代码有效:

    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
    }
    

    这也可以:

    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)
        }
    }
    

    在深度上,for(x &lt;- xs; y &lt;- ys; ...) yield f(...) 等价于xs.flatMap(...)List#flatMap 的完整签名如下:

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

    你可以看到flatMap的返回类型是一个ma​​gicThat,默认是List[B],你可以查看Scala 2.8 CanBuildFrom了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      相关资源
      最近更新 更多