最好的纯功能替代while循环

时间:2015-07-13 14:53:32

标签: scala

下面的代码是一个更好的功能习惯替代品吗?即是否有一种更简洁的方法来获取值j而不必使用var?

<div class="txt">
    This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. This is just a temporary text. 
</div>

2 个答案:

答案 0 :(得分:8)

val j = idxs.drop(i).indexWhere(_ != x) + i

或者,正如@kosii在评论中所建议的那样,使用indexWhere重载来获取从哪里开始搜索的索引:

val j = idxs.indexWhere(_ != x, i)

修改

由于j必须等于idxs的长度,以防i后的所有项都等于x

val index = idxs.indexWhere(_ != x, i)
val j = if(index < 0) idxs.length else index

// or

val j = if (idxs.drop(i).forall(_ == x)) idxs.length
        else idxs.indexWhere(_ != x, i)

答案 1 :(得分:0)

也许使用溪流,例如:

a = True