Skip to content

Commit efe1795

Browse files
authored
Merge pull request #1243 from fabiopakk/patch-1
More precise wording regarding 'pairs' example
2 parents d4889c2 + dd347a0 commit efe1795

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

_tour/for-comprehensions.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,19 @@ Here is a more complicated example using two generators. It computes all pairs o
3737
```tut
3838
def foo(n: Int, v: Int) =
3939
for (i <- 0 until n;
40-
j <- i until n if i + j == v)
40+
j <- 0 until n if i + j == v)
4141
yield (i, j)
4242
4343
foo(10, 10) foreach {
4444
case (i, j) =>
45-
println(s"($i, $j) ") // prints (1, 9) (2, 8) (3, 7) (4, 6) (5, 5)
45+
println(s"($i, $j) ") // prints (1, 9) (2, 8) (3, 7) (4, 6) (5, 5) (6, 4) (7, 3) (8, 2) (9, 1)
4646
}
4747
4848
```
4949
Here `n == 10` and `v == 10`. On the first iteration, `i == 0` and `j == 0` so `i + j != v` and therefore nothing is yielded. `j` gets incremented 9 more times before `i` gets incremented to `1`. Without the `if` guard, this would simply print the following:
5050
```
5151
52-
(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (1, 1) ...
52+
(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (1, 0) ...
5353
```
5454

5555
Note that comprehensions are not restricted to lists. Every datatype that supports the operations `withFilter`, `map`, and `flatMap` (with the proper types) can be used in sequence comprehensions.
@@ -59,7 +59,7 @@ You can omit `yield` in a comprehension. In that case, comprehension will return
5959
```tut
6060
def foo(n: Int, v: Int) =
6161
for (i <- 0 until n;
62-
j <- i until n if i + j == v)
62+
j <- 0 until n if i + j == v)
6363
println(s"($i, $j)")
6464
6565
foo(10, 10)

0 commit comments

Comments
 (0)