官术网_书友最值得收藏!

Currying

Speaking about partial application, we have not referred to one special case of this, currying. Currying is in a sense a partial application where we take a function of N arguments and apply partial application for each argument in a row each time, to produce a function that takes one argument less. We repeat this process until we're left with N functions, each taking one argument. If it sounds complicated, consider the next example of a function of two arguments: 

def sum(a: Int, b: Int) = a + b

 Using two parameter lists, we can rewrite it as follows:

def sumAB(a: Int)(b: Int) = a + b

The type of this method is (a: Int)(b: Int): Int or expressed as a function: 

:type sumAB _
Int => (Int => Int)

This is a function that takes an Int and returns a function from Int to Int! The number of arguments is not limited to just two of course:

scala> val sum6 = (a: Int) => (b: Int) => (c: Int) => (d: Int) => (e: Int) => (f: Int) => a + b + c + d+ e + f
sum6: Int => (Int => (Int => (Int => (Int => (Int => Int)))))

The placeholder syntax will give us the same functionality, but in uncurried form:

scala> val sum6Placeholder = (_: Int) + (_: Int) + (_: Int) + (_: Int) + (_: Int) + (_: Int)
sum6Placeholder: (Int, Int, Int, Int, Int, Int) => Int

Currying is not very important in Scala compared to some other functional programming languages, but it is good to know as a useful functional programming concept.

主站蜘蛛池模板: 达孜县| 凤城市| 濮阳县| 车险| 常宁市| 扬州市| 山东省| 湘潭市| 新安县| 莱芜市| 南召县| 泰宁县| 乐清市| 怀仁县| 塘沽区| 石景山区| 丰县| 伊吾县| 延安市| 湘阴县| 文昌市| 天门市| 扎赉特旗| 新绛县| 三台县| 吉林市| 申扎县| 铜陵市| 麻栗坡县| 汪清县| 鲁甸县| 湖口县| 广安市| 黑山县| 陆丰市| 繁昌县| 九龙坡区| 彰化市| 沽源县| 古交市| 新巴尔虎左旗|