如何将函数结果传递给 math.max
How to pass Function result to math.max
我能做到:
def largestAt(fun: (Int) => Int, inputs: Seq[Int]):Int = {
inputs.reduceLeft(math.max(_,_))
}
但是,当我尝试这样做时:
def largestAt(fun: (Int) => Int, inputs: Seq[Int]):Int = {
inputs.reduceLeft(math.max(fun(_),fun(_)))
}
我遇到下面提到的编译错误:
overloaded method value max with alternatives:
[error] (x: Double,y: Double)Double <and>
[error] (x: Float,y: Float)Float <and>
[error] (x: Long,y: Long)Long <and>
[error] (x: Int,y: Int)Int
[error] cannot be applied to (Int => Int, Int => Int)
[error] inputs.reduceLeft(math.max(fun(_),fun(_)))
我只想将 fun
的结果传递给 math.max
调用。我怎样才能做到这一点。
提前致谢...
表达式中的匿名函数占位符参数语法
inputs.reduceLeft(math.max(fun(_),fun(_)))
扩展为
inputs.reduceLeft(math.max(a => fun(a), b => fun(b)))
和 max
不将一对函数作为输入。相反,您可能会追求
inputs.reduceLeft((a, b) => math.max(fun(a), fun(b)))
另一方面,下划线的以下用法有效
inputs.reduceLeft(math.max(_, _))
因为它扩展到
inputs.reduceLeft((a, b) => math.max(a, b))
应该谨慎使用占位符语法,正确使用它的关键是理解 :
If the underscore is inside an expression delimited by () or {}, the
innermost such delimiter that contains the underscore will be used;
我能做到:
def largestAt(fun: (Int) => Int, inputs: Seq[Int]):Int = {
inputs.reduceLeft(math.max(_,_))
}
但是,当我尝试这样做时:
def largestAt(fun: (Int) => Int, inputs: Seq[Int]):Int = {
inputs.reduceLeft(math.max(fun(_),fun(_)))
}
我遇到下面提到的编译错误:
overloaded method value max with alternatives:
[error] (x: Double,y: Double)Double <and>
[error] (x: Float,y: Float)Float <and>
[error] (x: Long,y: Long)Long <and>
[error] (x: Int,y: Int)Int
[error] cannot be applied to (Int => Int, Int => Int)
[error] inputs.reduceLeft(math.max(fun(_),fun(_)))
我只想将 fun
的结果传递给 math.max
调用。我怎样才能做到这一点。
提前致谢...
表达式中的匿名函数占位符参数语法
inputs.reduceLeft(math.max(fun(_),fun(_)))
扩展为
inputs.reduceLeft(math.max(a => fun(a), b => fun(b)))
和 max
不将一对函数作为输入。相反,您可能会追求
inputs.reduceLeft((a, b) => math.max(fun(a), fun(b)))
另一方面,下划线的以下用法有效
inputs.reduceLeft(math.max(_, _))
因为它扩展到
inputs.reduceLeft((a, b) => math.max(a, b))
应该谨慎使用占位符语法,正确使用它的关键是理解
If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used;