scala, Passing an operator as argument of a function

前端 未结 3 986
说谎
说谎 2021-02-20 08:06

I have this code:

for( i <- 0 to 8){
  ((numbers(i) - i)/3).abs + ((numbers(i) - i)%3).abs
}

and I would like to do, as the title says, some

3条回答
  •  一整个雨季
    2021-02-20 08:33

    To get rid of the underscores you need to define the functions as values.

    val / = (a:Int, b: Int) => a / b
    val % = (a:Int, b: Int) => a % b
    
    def by3(a: Int, b: Int, fn: (Int, Int) => Int): Int = fn(a - b, 3).abs
    
    (0 to 8).foreach(i => by3(numbers(i), i, /) + by3(numbers(i), i, %))
    

提交回复
热议问题