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

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

主站蜘蛛池模板: 泗阳县| 延吉市| 太白县| 五华县| 清流县| 林西县| 遵义市| 巴林左旗| 安多县| 河曲县| 长垣县| 新营市| 永泰县| 仪陇县| 榆树市| 阳东县| 海晏县| 舒兰市| 甘南县| 周至县| 吴桥县| 营口市| 安阳县| 宝兴县| 常宁市| 丹江口市| 溆浦县| 资兴市| 湄潭县| 德阳市| 永新县| 西盟| 武威市| 井研县| 巴塘县| 靖西县| 天镇县| 绥宁县| 内丘县| 海丰县| 九寨沟县|