Skip to content

Commit 564dcfe

Browse files
authored
Merge pull request #78 from hellrich/patch-pattern-matching
Added another example and some comments
2 parents 04fbeb9 + ec11b41 commit 564dcfe

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

src/main/scala/stdlib/PatternMatching.scala

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de
1515
* def matchTest(x: Int): String = x match {
1616
* case 1 => "one"
1717
* case 2 => "two"
18-
* case _ => "many"
18+
* case _ => "many" // case _ will trigger if all other cases fail.
1919
* }
20-
* println(matchTest(3))
20+
* println(matchTest(3)) // prints "many"
2121
* }
2222
* }}}
2323
*
@@ -38,7 +38,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de
3838
println("BLUE"); 2
3939
case "green"
4040
println("GREEN"); 3
41-
case _ println(stuff); 0 //case _ will trigger if all other cases fail.
41+
case _ println(stuff); 0 // case _ will trigger if all other cases fail.
4242
}
4343

4444
myStuff should be(res0)
@@ -178,7 +178,7 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de
178178
*/
179179
def againstListsIIIPatternMatching(res0: Int) {
180180
val secondElement = List(1) match {
181-
case x :: y :: xs y
181+
case x :: y :: xs y // only matches a list with two or more items
182182
case _ 0
183183
}
184184

@@ -189,11 +189,22 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de
189189
*/
190190
def againstListsIVPatternMatching(res0: Int) {
191191
val r = List(1, 2, 3) match {
192-
case x :: y :: Nil y
192+
case x :: y :: Nil y // only matches a list with exactly two items
193193
case _ 0
194194
}
195195

196196
r should be(res0)
197197
}
198198

199+
/** If a pattern is exactly one element longer than a `List`, it extracts the final `Nil`:
200+
*/
201+
def againstListsVPatternMatching(res0: Boolean) {
202+
val r = List(1, 2, 3) match {
203+
case x :: y :: z :: tail tail
204+
case _ 0
205+
}
206+
207+
r == Nil should be(res0)
208+
}
209+
199210
}

src/test/scala/stdlib/PatternMatchingSpec.scala

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,14 @@ class PatternMatchingSpec extends Spec with Checkers {
105105
)
106106
)
107107
}
108+
109+
def `pattern matching lists part five` = {
110+
check(
111+
Test.testSuccess(
112+
PatternMatching.againstListsVPatternMatching _,
113+
true :: HNil
114+
)
115+
)
116+
}
117+
108118
}

0 commit comments

Comments
 (0)