scala,将运算符作为函数的参数传递 [英] scala, Passing an operator as argument of a function

查看:36
本文介绍了scala,将运算符作为函数的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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, something like this

for( i <- 0 to 8){
  by3(numbers(i), i, /) + by3(numbers(i), i, %)
}

def by3(a: Int, b: Int, op: Int => Int) = ((a - b) op 3).abs

并且可能还为此使用了部分应用函数..但是现在这可以实现吗?怎么样?

and probably also use a partially applied function for it.. but by now this would be possible to achieve? How?

推荐答案

要去掉下划线,您需要将函数定义为值.

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, %))

这篇关于scala,将运算符作为函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆