开发者

Scala: Rewrite code duplication with closures

I have this code:

val arr: Array[Int] = ...
val largestIndex = {
  var i = arr.length-2
  while (arr(i) > arr(i+1)) i -= 1
  i
}
val smallestIndex = {
  var k = arr.length-1
  while (arr(largestIndex) > arr(k)) k -= 1
  k
}

But there is to much code duplication. I tried to rewrite this with closures but I failed. I tried something like this:

def index(sub: Int, f: => Boolean): Int = {
  var i = arr.length-sub
  while (f) i -= 1
  i
}
va开发者_Python百科l largest = index(2, i => arr(i) > arr(i+1))
val smallest = index(1, i => arr(largest) > arr(i))

The problem is that i can't use parameter i of the method index() in the closure. Is there a way to avoid this problem?


val arr = Array(1,2,4,3,3,4,5)
def index(sub: Int, f: Int => Boolean): Int = {
  var i = arr.length-sub                       
  while (f(i)) i -= 1                          
  i                                            
}                                              
val largest = index(2, i => arr(i) > arr(i+1))
val smallest = index(1, i => arr(largest) > arr(i))


val arr = Array(1,2,4,3,3,4,5)
arr: Array[Int] = Array(1, 2, 4, 3, 3, 4, 5)

scala> arr.zipWithIndex.max(Ordering.by((x: (Int, Int)) => x._1))._2
res0: Int = 6

scala> arr.zipWithIndex.min(Ordering.by((x: (Int, Int)) => x._1))._2
res1: Int = 0

or

scala> val pairOrdering = Ordering.by((x: (Int, Int)) => x._1)
pairOrdering: scala.math.Ordering[(Int, Int)] = scala.math.Ordering$$anon$4@145ad3d

scala> arr.zipWithIndex.max(pairOrdering)._2
res2: Int = 6

scala> arr.zipWithIndex.min(pairOrdering)._2
res3: Int = 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜