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

  • 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.

主站蜘蛛池模板: 崇仁县| 辽源市| 安化县| 章丘市| 长白| 龙山县| 玛曲县| 长丰县| 平安县| 汶上县| 丽江市| 大姚县| 和政县| 东光县| 金昌市| 建宁县| 江门市| 蕲春县| 九龙坡区| 温泉县| 临漳县| 宁蒗| 朝阳县| 黎川县| 霍州市| 东辽县| 平安县| 富宁县| 双柏县| 嘉峪关市| 白玉县| 庆元县| 河北省| 临高县| 孝感市| 洞头县| 寻甸| 吉水县| 大厂| 大理市| 台东市|