3

I'm trying to concatenate 3 sequences as results of individual for loops with yield. I can't get it to work without temporary variables. Does anybody know a better option? The notWorking version gives me a compiler error at the fourth line of the method "illegal start of a simple expression" just after the first ++.

def working() : Seq[Seq[Elem]] = {
    val result = for(index <- 0 until COMPLETE_INPUT_CHANNELS) yield {
        getModesOfCompleteInputChannel(index)
    }
    val result2 = for(index <- 0 until INCOMPLETE_INPUT_CHANNELS) yield {
        getModesOfIncompleteInputChannel(index)
    }
    val result3 = for(index <- 0 until OUTPUT_CHANNELS) yield {
        getModesOfOutputChannel(index)
    }
    return result ++ result2 ++ result3
}

def notWorking() : Seq[Seq[Elem]] = {
    for(index <- 0 until COMPLETE_INPUT_CHANNELS) yield {
        getModesOfCompleteInputChannel(index)
    } ++ for(index <- 0 until INCOMPLETE_INPUT_CHANNELS) yield {
        getModesOfIncompleteInputChannel(index)
    } ++ for(index <- 0 until OUTPUT_CHANNELS) yield {
        getModesOfOutputChannel(index)
    }
4

3 回答 3

15

这个解决方案怎么样?

val tasks = Seq(
    (COMPLETE_INPUT_CHANNELS, getModesOfOutputChannel),
    (INCOMPLETE_INPUT_CHANNELS, getModesOfIncompleteInputChannel),
    (OUTPUT_CHANNELS, getModesOfOutputChannel))

tasks flatMap {
    case (limit, processing) => 0 until limit map processing
}
于 2012-11-27T12:45:07.263 回答
6

为什么不是这个?

(0 until COMPLETE_INPUT_CHANNELS).map(getModesOfCompleteInputChannel) ++
(0 until COMPLETE_INPUT_CHANNELS).map(getModesOfIncompleteInputChannel) ++
(0 until OUTPUT_CHANNELS).map(getModesOfOutputChannel)

虽然我确实喜欢 MAD 的解决方案。十分优雅。

于 2012-11-27T12:47:16.497 回答
2

我相信,++这里被视为yield表达式的一部分。为了使它起作用,只需将您的for理解用括号括起来。

于 2012-11-27T12:44:04.910 回答