Scala 高阶函数混淆

Scala HIGHER-ORDER FUNCTIONS confuse

在学习 Scala 时,我从这里得到了一个高阶函数的例子

https://docs.scala-lang.org/tour/higher-order-functions.html

def apply(f : Int => String, v : Int) = f(v)
def layout[A](x : A) : String = x.toString
println(apply(layout, 1000))

我的问题是布局是否有超过 1 个参数,如下所示:

def layout[A](x : A, y : A) : String = x.toString + y.toString

为了直观理解,我定义apply如下

def apply(f : Int, Int => String, v : Int, w : Int) = f(v, w)

当然,这个是不能编译的。 我觉得我对Scala中函数类型的理解有偏差

How to solve this problem with the right position,和 Solve this problem with the right position,再深入了解一下scala函数类型的定义就好了。

只需在参数两边加上括号

def apply(f : (Int, Int) => String, v1 : Int, v2: Int) = f(v1, v2)

阅读有关 scala 中的函数特征的信息,那里有 22 个函数特征(Function0、Function1、.....Function2),适合您的情况: http://www.scala-lang.org/api/2.12.3/scala/Function2.html

也在Java8中了解函数式接口,然后尝试与 Scala 函数特性进行比较。

我来举个例子

   package scalaLearning

  object higherOrderFunctions {

  def main(args: Array[String]): Unit = {

  def add(a: Int , b:Int):Int =a+b //Function to add integers which two int  values and return and int value
  def mul(a:Int, b:Int ) :Float=a*b //Function which takes two int values and return float value
  def sub(a:Int,b:Int):Int=a-b //function which takes two int values and return int value
  def div(a:Int,b:Int):Float =a/b//Function which takes two int value and return float value

 def operation(function:(Int,Int)=>AnyVal,firstParam:Int,secondParam:Int):AnyVal=function(firstParam,secondParam)   //Higher order function

 println(operation(add,2,4))
 println(operation(mul,2,4))

 println(operation(sub,2,4))
 println(operation(div,2,4))
}
}

此处在创建以输入为函数的高阶函数时,

首先你需要了解你的参数函数的输入类型 需要什么 returns,

在我的例子中,它需要两个 int 值,return float 或 int,所以你可以 提及函数_:(Int,Int) => AnyVal

并把参数传给你指定的这个函数 firstParam:Int(Thiscould also be firstParam:AnyVal) 作为第一个参数并指定

secondParam:Int(这也可以是 secondParam:AnyVal) 作为第二个参数。

   def operation(function(Int,Int)=>AnyVal,firstParam:Int,secondParam:Int):AnyVal=function(firstParam,secondParam)   //Higher order function