Skip to content

Commit 290876f

Browse files
authored
Add code tabs for _tour/for-comprehensions (#2536)
* Add code tabs for _tour/for-comprehensions * Update for-comprehensions.md * Update for-comprehensions.md
1 parent 44c9e28 commit 290876f

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

_tour/for-comprehensions.md

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ val twentySomethings =
3434
twentySomethings.foreach(println) // prints Travis Dennis
3535
```
3636
{% endtab %}
37-
3837
{% tab 'Scala 3' for=for-comprehensions-01 %}
3938
```scala
4039
case class User(name: String, age: Int)
@@ -54,7 +53,6 @@ twentySomethings.foreach(println) // prints Travis Dennis
5453
{% endtab %}
5554
{% endtabs %}
5655

57-
5856
A `for` loop with a `yield` statement returns a result, the container type of which is determined by the first generator. `user <- userBase` is a `List`, and because we said `yield user.name` where `user.name` is a `String`, the overall result is a `List[String]`. And `if user.age >=20 && user.age < 30` is a guard that filters out users who are not in their twenties.
5957

6058
Here is a more complicated example using two generators. It computes all pairs of numbers between `0` and `n-1` whose sum is equal to a given value `v`:
@@ -71,23 +69,19 @@ foo(10, 10).foreach {
7169
case (i, j) =>
7270
println(s"($i, $j) ") // prints (1, 9) (2, 8) (3, 7) (4, 6) (5, 5) (6, 4) (7, 3) (8, 2) (9, 1)
7371
}
74-
7572
```
7673

7774
{% endtab %}
78-
7975
{% tab 'Scala 3' for=for-comprehensions-02 %}
8076
```scala
8177
def foo(n: Int, v: Int) =
82-
for i <- 0 until n
83-
j <- 0 until n if i + j == v
78+
for i <- 0 until n
79+
j <- 0 until n if i + j == v
8480
yield (i, j)
8581

8682
foo(10, 10).foreach {
87-
case (i, j) =>
88-
println(s"($i, $j) ") // prints (1, 9) (2, 8) (3, 7) (4, 6) (5, 5) (6, 4) (7, 3) (8, 2) (9, 1)
83+
(i, j) => println(s"($i, $j) ") // prints (1, 9) (2, 8) (3, 7) (4, 6) (5, 5) (6, 4) (7, 3) (8, 2) (9, 1)
8984
}
90-
9185
```
9286
{% endtab %}
9387
{% endtabs %}
@@ -116,16 +110,15 @@ foo(10, 10)
116110
{% tab 'Scala 3' for=for-comprehensions-03 %}
117111
```scala
118112
def foo(n: Int, v: Int) =
119-
for i <- 0 until n
120-
j <- 0 until n if i + j == v
113+
for i <- 0 until n
114+
j <- 0 until n if i + j == v
121115
do println(s"($i, $j)")
122116

123117
foo(10, 10)
124118
```
125119
{% endtab %}
126120
{% endtabs %}
127121

128-
129122
## More resources
130123

131124
* Other examples of "For comprehension" in the [Scala Book](/overviews/scala-book/for-expressions.html)

0 commit comments

Comments
 (0)