Anonymous Scala function syntax

前端 未结 3 443
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 18:17

I\'m learning more about Scala, and I\'m having a little trouble understanding the example of anonymous functions in http://www.scala-lang.org/node/135. I\'ve copied the ent

3条回答
  •  悲&欢浪女
    2020-12-28 18:52

    This is a fun thing in functional programming called currying. Basically Moses Schönfinkel and latter Haskell Curry (Schonfinkeling would sound weird though...) came up with the idea that calling a function of multiple arguments, say f(x,y) is the same as the chain of calls {g(x)}(y) or g(x)(y) where g is a function that produces another function as its output.

    As an example, take the function f(x: Int, y: Int) = x + y. A call to f(2,3) would produce 5, as expected. But what happens when we curry this function - redefine it as f(x:Int)(y: Int)and call it as f(2)(3). The first call, f(2) produces a function taking an integer y and adding 2 to it -> therefore f(2) has type Int => Int and is equivalent to the function g(y) = 2 + y. The second call f(2)(3) calls the newly produced function g with the argument 3, therefore evaluating to 5, as expected.

    Another way to view it is by stepping through the reduction (functional programmers call this beta-reduction - it's like the functional way of stepping line by line) of the f(2)(3) call (note, the following is not really valid Scala syntax).

    f(2)(3)         // Same as x => {y => x + y}
     | 
    {y => 2 + y}(3) // The x in f gets replaced by 2
           |
         2 + 3      // The y gets replaced by 3
           |
           5
    

    So, after all this talk, f(x)(y) can be viewed as just the following lambda expression (x: Int) => {(y: Int) => x + y} - which is valid Scala.

    I hope this all makes sense - I tried to give a bit of a background of why the modN(3) call makes sense :)

提交回复
热议问题