- 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.
- .NET之美:.NET關鍵技術深入解析
- Intel Galileo Essentials
- LabVIEW入門與實戰開發100例
- Rust編程:入門、實戰與進階
- Programming ArcGIS 10.1 with Python Cookbook
- 技術領導力:程序員如何才能帶團隊
- Raspberry Pi for Secret Agents(Third Edition)
- HBase從入門到實戰
- 數據結構(Python語言描述)(第2版)
- Securing WebLogic Server 12c
- Learning Hunk
- Learning JavaScript Data Structures and Algorithms
- Java Web開發詳解
- 監控的藝術:云原生時代的監控框架
- Java 9 with JShell