2014-11-02 43 views
0

我可以將最內部for正文的結果收集到List[Output]並返回它們。但我想用yield。如何這種方法被轉換成使用for-yield圖案:將嵌套for循環轉換爲理解

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

[我得到完全不同的錯誤](http://scalafiddle.net/console/4e38d30e656da5ae9d3a425109ce9e04),這讓我覺得你的例子是錯誤的(顯示你的問題的代碼不在那個問題中),或者你有相當老的scala版本,因爲在最近的scala版本中,你不能在'{}'裏面有'yield'(它必須是第一條語句) – 2014-11-02 04:58:39

+0

我正在學習yield的使用。我怎麼才能完成上述功能(儘管代碼不能編譯,你能得到我的意圖嗎?)正確使用yield? – 2014-11-02 15:27:21

+0

寫'yield {...}'不是'{yield ...}' – 2014-11-04 05:47:56

回答

1

在Scala中,嵌套迭代通過添加額外的<-條款處理。

例如,假設我們有兩個列表l1l2,我們要產生超過每對元素(x,y)的地方xl1yl2。 Scala中的語法是:

for { x <- l1 
     y <- l2 
    } yield (x,y) 

當沒有yield關鍵字跟隨for然後整個表達式的類型的Unit,這是您的類型錯誤的來源的結果。這是在迭代執行的副作用非常有用,例如

for { x <- l1 
     y <- l2 
    } println((x,y)) 

有關爲內涵看What is Scala's yield?

+0

我明白了。我已經嘗試了幾次來將'<-'合併爲一個'for',但失敗了。你能轉換我的代碼嗎? – 2014-11-02 15:24:20

+0

你能發佈你試過的代碼不成功嗎?也許在問題中錯過了其他錯誤。 – lea 2014-11-02 17:01:45

0

你的錯誤可能是因爲您在{}周圍產生更多的信息。

for {stuff} {yield otherstuff} 

的形式應該是:

for {stuff} yield otherstuff 

你當然可以取代「otherstuff」與塊,如果你希望它包含多個表達式,所以你必須:

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