我认为这不可能,但也许我错过了什么?
这是一个例子
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)
}
这可以翻译成for-comprehension表达式吗?
我注意到,当我在期货上使用map / flatMap时(例如在webservice调用上),如果我需要对服务响应进行模式匹配,我会经常使用这种模式。所以我正在努力提高可读性。
谢谢:)
答案 0 :(得分:1)
您可以将外部构造转换为for / yield,将if / else的分支转换为/ yield:
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
成为具有子类的对象来使用多态,以便分支成为方法调用。但总的来说,如果分支之间没有任何共同点,那么你必须单独处理它们(这是有道理的,不是吗?)。