2015-07-01 24 views
0

我認爲這是不可能的,但也許我錯過了什麼?可以將具有多條路徑的map/flatMap序列翻譯爲理解嗎?

下面是一個例子

val sentences = "hello.what is your name?I am Loïc"  

sentences.split("\\.|\\?").flatMap { sentence => 
    if (sentence.startsWith("h")) sentence.split(" ").map(word => word.toUpperCase) 
    else if (sentence.startsWith("w")) sentence.split(" ").flatMap(word => List(word.toUpperCase, "-").map(word => word.toUpperCase)) 
    else List(sentence) 
} 

可以這樣被轉化爲一個換理解表達?

我注意到,當我在期貨上使用map/flatMap時(例如在webservice調用上),我需要對服務響應進行模式匹配時,我經常使用這種模式。所以我試圖提高可讀性。

謝謝:)

+0

「理解表達」的含義是什麼?你想要將flatMap轉換爲foreach循環? – eliasah

+0

@eliasah我的意思是這樣的{ 書< - 書籍 如果book.author startsWith 「鮑勃」 }收率book.title 可以在 books.filter(書=翻譯> book.author startsWith 「鮑勃」 ).map(book => book.title) – Loic

回答

1

可以轉換外構造成用於/產量,以及分支的if/else到自己的/收益率:

for { 
    sentence ← sentences.split("\\.|\\?") 
    out ← if (sentence.startsWith("h")) 
     for {word ← sentence.split(" ")} yield word.toUpperCase 
    else if (sentence.startsWith("w")) 
     for {word ← sentence.split(" ") 
      w ← List(word.toUpperCase, "-") } yield w.toUpperCase 
    else List(sentence) 
} yield out 

如果你可以提取一些共性從分支你可能能夠將它們組合成單個高階函數調用而不是if/else,例如通過使用scalaz的traverse,或通過使用多態性使sentence成爲具有子類的對象,以便分支變成方法調用。但是一般來說,如果分支之間沒有共同之處,那麼你將不得不單獨處理它們(這是有道理的,不是?)。

相關問題