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

  • Learn Scala Programming
  • Slava Schmidt
  • 278字
  • 2021-06-10 19:35:49

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.

主站蜘蛛池模板: 寿光市| 霸州市| 南澳县| 吴旗县| 米泉市| 英吉沙县| 台东市| 绵竹市| 台州市| 丰宁| 上蔡县| 马边| 锦州市| 开江县| 万山特区| 靖宇县| 高陵县| 东港市| 峡江县| 富民县| 若尔盖县| 峨边| 财经| 德庆县| 读书| 崇明县| 临沂市| 华蓥市| 嘉义市| 正镶白旗| 汪清县| 龙泉市| 江山市| 宁德市| 临高县| 永寿县| 巴南区| 始兴县| 安达市| 门源| 陆良县|