Skip to content

Commit b5fb699

Browse files
author
sujithjay
committed
Partial function reuse
1 parent 327241a commit b5fb699

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

_tour/multiple-parameter-lists.md

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,20 +25,42 @@ def foldLeft[B](z: B)(op: (B, A) => B): B
2525

2626
```tut
2727
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
28-
val res = numbers.foldLeft(0)((m: Int, n: Int) => m + n)
28+
val res = numbers.foldLeft(0)((m, n) => m + n)
2929
print(res) // 55
3030
```
3131

32-
Starting with an initial value of 0, `foldLeft` applies the function `(m: Int, n: Int) => m + n` to each element in the List and the previous accumulated value.
32+
Starting with an initial value of 0, `foldLeft` applies the function `(m, n) => m + n` to each element in the List and the previous accumulated value.
3333

3434
Multiple parameter lists have a more verbose invocation syntax; and hence should be used sparingly. Suggested use cases include:
3535

36-
1. ##### Implicit parameters
36+
1. ##### Single functional parameter
37+
In case of a single functional parameter, like `op` in the case of `foldLeft` above, multiple parameter lists allow a concise syntax to pass an anonymous function to the method. Without multiple parameter lists, the code would look like this:
38+
```
39+
numbers.foldLeft(0, {(m: Int, n: Int) => m + n})
40+
```
41+
Note that the use of multiple parameter lists here also allows us to take advantage of Scala type inference to make the code more concise as shown below; which would not be possible for a non-curried definition.
42+
43+
```
44+
numbers.foldLeft(0)(_ + _)
45+
```
46+
47+
Also, it allows us to fix the parameter `z` and pass around a partial function and reuse it as shown below:
48+
```tut
49+
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
50+
val numberFunc = numbers.foldLeft(List[Int]())_
51+
52+
val squares = numberFunc((xs, x) => xs:+ x*x)
53+
print(squares.toString()) // List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
54+
55+
val cubes = numberFunc((xs, x) => xs:+ x*x*x)
56+
print(cubes.toString()) // List(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000)
57+
```
58+
59+
2. ##### Implicit parameters
3760
To specify certain parameters in a parameter list as `implicit`, multiple parameter lists should be used. An example of this is:
3861
3962
```
4063
def execute(arg: Int)(implicit ec: ExecutionContext) = ???
4164
```
4265
43-
2. ##### Single functional parameter
44-
In case of a single functional parameter, like `op` in the case of `foldLeft` above, multiple parameter lists allow a concise syntax to pass an anonymous function to the method.
66+
2.

0 commit comments

Comments
 (0)