将嵌套for循环转换为for comprehension

时间:2014-11-02 03:56:34

标签: scala for-comprehension

我可以将最里面for身体的结果收集到List[Output]并返回它们。但我想使用yield。如何将此方法转换为使用for-yield模式:

def useForComprehension(input : Input): List[Output] = {        
  for (o <- splitInputIntoPieces(input)) {
    for (restResults <- useForComprehension(subtract(input, o)) ) {
        for (w <- f3(o)) {
          yield w::restResults // !!!!! Error
        }
    }           
  }    
}

2 个答案:

答案 0 :(得分:3)

在Scala中,通过添加其他<-子句来处理嵌套迭代。

例如,我们假设我们有两个列表l1l2,我们希望生成(x,y)所在的每个元素x { {1}}和l1位于y。 Scala中的语法是:

l2

如果for { x <- l1 y <- l2 } yield (x,y) 后面没有yield个关键字,则整个表达式会生成for类型,这是类型错误的来源。这对于对迭代执行副作用很有用,例如

Unit

有关理解的更多信息,请参阅What is Scala's yield?

答案 1 :(得分:0)

您的错误可能是因为您在{}中围绕收益率。

for {stuff} {yield otherstuff}

表格应为:

for {stuff} yield otherstuff

你当然可以取代&#34;其他的话&#34;如果你想让它包含多个表达式,你可以使用一个块:

for {stuff} yield {otherstuff}

使用你的例子我怀疑你想要的东西:

def useForComprehension(input: Input): List[Output] =
  for {
    o <- splitInputIntoPieces(input)
    restResults <- useForComprehension(subtract(input, o))
    w <- f3(o)
  } yield w :: restResults