- 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.
- R語言經典實例(原書第2版)
- Docker進階與實戰
- 實戰Java程序設計
- C#程序設計(慕課版)
- Learn Scala Programming
- R的極客理想:工具篇
- Android底層接口與驅動開發技術詳解
- Access 2010數據庫應用技術(第2版)
- Learning R for Geospatial Analysis
- 運維前線:一線運維專家的運維方法、技巧與實踐
- Kotlin Programming By Example
- Getting Started with Python
- CodeIgniter Web Application Blueprints
- 深入分析GCC
- ABAQUS6.14中文版有限元分析與實例詳解