前如何使下面的非功能性的,但简单的代码更多的功能:退出循环结束
def foo2(iSeq: Seq[Int]): Seq[(Int, Boolean)] = {
var seq = Seq[(Int, Boolean)]()
iSeq.foreach{ i=>
println("i = " + i)
val res = (i,i>=0)
seq = seq ++ Seq(res)
if (res._2==false) return seq
}
seq
}
代码的想法是循环给出序列,直到第一次测试失败,没有进一步的,因为在真实的代码测试是昂贵的。返回的seq应包含所有项目,包括失败的项目。代码
输出如下:
scala> foo2(Seq(1,2,-3,4))
i = 1
i = 2
i = -3
res3: Seq[(Int, Boolean)] = List((1,true), (2,true), (-3,false))
scala> foo2(Seq(1,2,3,4))
i = 1
i = 2
i = 3
i = 4
res4: Seq[(Int, Boolean)] = List((1,true), (2,true), (3,true), (4,true))
我做了以下的第一次尝试:
def fooo(iTail: Seq[Int], resSeq: Seq[(Int,Boolean)]): Seq[(Int,Boolean)] = {
if (iTail.isEmpty) return resSeq
if (!resSeq.isEmpty && resSeq.last._1<0) return resSeq
println("i = " + iTail.head)
val res = (iTail.head,iTail.head>=0)
val seq = resSeq ++ Seq(res)
fooo(iTail.tail, seq)
}
输出是:
scala> fooo(Seq(1,2,3,4,5),Seq())
i = 1
i = 2
i = 3
i = 4
i = 5
res0: Seq[(Int, Boolean)] = List((1,true), (2,true), (3,true), (4,true), (5,true))
scala> fooo(Seq(1,2,-3,4,5),Seq())
i = 1
i = 2
i = -3
res1: Seq[(Int, Boolean)] = List((1,true), (2,true), (-3,false))
所以它的工作原理,但有一个更简洁或“无用”的方式来编码?
关于性能:代码使用resSeq.last。在递归函数fooo中使用额外的“lastValue”参数比使用resSeq.last更快吗?
IDK约惯用的,但早期的回报可能不应该在这样的一条线被挤满。我会用大括号将它扩展到一个完整的if/else树,以使它更清晰,可以在不执行函数的下半部分的情况下退出。 – Carcigenicate