如何编写在Scala中返回函数的非平凡函数?

如何编写在Scala中返回函数的非平凡函数?,scala,Scala,在Javascript中,我将编写一个高阶函数,以这种方式返回另一个函数: var f = function(x) { return function(y) { // something using x and y } } 这方面的Scala语法似乎是: def f(x: Any)(y: Any) = // Something with x and y 如果您在创建返回函数之前不需要做任何事情,这是很好的。但是,假设在创建返回函数之前必须以某种方式处理x(Javascript

在Javascript中,我将编写一个高阶函数,以这种方式返回另一个函数:

var f = function(x) {
  return function(y) {
    // something using x and y
  }
}
这方面的Scala语法似乎是:

def f(x: Any)(y: Any) = // Something with x and y
如果您在创建返回函数之前不需要做任何事情,这是很好的。但是,假设在创建返回函数之前必须以某种方式处理x(Javascript中的示例):


这一点还不清楚。

您可以解释返回函数,而不是使用单独的参数列表,例如

def f(x: Any) = {
    //something using x
    (y: Any) => //something with x and y
}


例如,调用以下函数:

def hof(i:Int) = (x:Int) => x + i
返回一个
Int=>Int
函数,该函数将接受
Int
并返回
Int
。对于您的情况,您可以这样做:

 def hof(i:Int) = {
    // do some other stuff....

   (x:Int) => i + x  //the last statement, so this function will be returned. 
 }

正如@Chirlo所说,
Int=>Int
表示函数

A=>B
只是trait
function[A,B]
where的语法糖

  • A
    输入类型
  • B
    输出类型
  • 功能n
    根据输入的数量而变化:接受1个输入,接受2个输入
以奇洛为例

def hof(i:Int) = {
    // do some other stuff....

   (x:Int) => i + x  //the last statement, so this function will be returned. 
 }
,这相当于

def hof = new Function1[Int,Function1[Int,Int]] {   
    def apply(i:Int) = new Function1[Int,Int] {     
        def apply(x:Int) = i + x 
    }
}

您提到的语法用于方法。改为查看lambdas:谢谢链接!我不知道方法和函数的语法是不同的。谢谢,但这并不能真正回答问题。我正在寻找如何在构造返回函数之前在初始调用中执行一些逻辑。值得一提的是,第二个版本将在每次调用返回函数时使用x执行
某些东西,而第一个版本只执行一次。@Chirlo-不,不会发生这种情况
val g=f(“x”);g(123);g(456)
只会执行
f
中的任何效果一次。你说得很对,x lambda当然会返回y lambda,而不是整个
{/code>块!
def hof(i:Int) = {
    // do some other stuff....

   (x:Int) => i + x  //the last statement, so this function will be returned. 
 }
def hof = new Function1[Int,Function1[Int,Int]] {   
    def apply(i:Int) = new Function1[Int,Int] {     
        def apply(x:Int) = i + x 
    }
}