函数文字 - 需要帮助理解代码片段

Raj*_*Raj 1 scala

我基本上不熟悉函数式编程和scala,以下问题可能看起来很愚蠢.

val f = (a:Int) => a+1
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我应该考虑f成为函数还是变量?来自C/C++背景,发生的第一个想法是f存储匿名函数的返回值的变量,但我认为这不是解释它的正确方法.任何解释都会非常有用.

(我上面使用的一些术语在scala /函数式编程方面可能是错误的,请耐心等待)

dhg*_*dhg 5

f是一个存储函数的变量.这与说下列任何一点没什么不同:

val a = 4               // `a` is a variable storing an Int
val b = "hi"            // `b` is a variable storing a String
val f = (a:Int) => a+1  // `f` is a variable storing a function
Run Code Online (Sandbox Code Playgroud)

您也可以使用REPL确认:

scala> val f = (a:Int) => a+1
f: Int => Int = <function1>
Run Code Online (Sandbox Code Playgroud)

所以这告诉你f有类型Int => Int.换句话说,f是一个函数,它接受一个参数,一个Int,并返回一个Int.

既然f是变量,您可以在其上调用方法或将其作为参数传递给期望其类型的函数:

a + 3  // here I'm calling the `+` method on `a`, which is an Int
f(3)   // here I'm calling the `apply` method on `f`, which is a function `Int => Int`
f(a)   // the function `f` expects an `Int`, which `a` is
(1 to 3).map(f)  // the `map` method expects a function from Int to Int, like `f`
Run Code Online (Sandbox Code Playgroud)

  • @ 0__:Scala规范使用"变量"这个词,即使值不能改变,就像Haskell规范,几乎每个数学教科书一样,等等.你可能认为标准用法可能有点混乱,但试图改变它不是一场你将要赢的战斗. (2认同)