From 9fa4664f3c91047c7e48c5870744688284a055dd Mon Sep 17 00:00:00 2001 From: Arkadiusz Chudoba <32493191+ArkadiuszChudoba@users.noreply.github.com> Date: Tue, 18 Dec 2018 11:28:23 +0100 Subject: [PATCH] Fixing Traversables.scala groupBy example There were two problems with groupBy example: 1. It didn't work properly for negative numbers. 2. partial functions were unnecessarily complicated as we could use the fact that we chain partial functions. This has added benefit of showing how partial functions can be chained to perform more specific grouping. --- src/main/scala/stdlib/Traversables.scala | 34 +++++++++++++----------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/scala/stdlib/Traversables.scala b/src/main/scala/stdlib/Traversables.scala index 70fa4605..3199fdde 100644 --- a/src/main/scala/stdlib/Traversables.scala +++ b/src/main/scala/stdlib/Traversables.scala @@ -364,39 +364,41 @@ object Traversables extends FlatSpec with Matchers with org.scalaexercises.defin /** `groupBy` will categorize a `Traversable` according to a given function and return a map with the results. This exercise uses partial function chaining: */ - def groupByFunctionTraversables(res0: Int, res1: Int) { - val array = Array(87, 44, 5, 4, 200, 10, 39, 100) + def groupByFunctionTraversables(res0: Int, res1: Int, res2: Int, res3: Int) { + val array = Array(87, 44, 5, 4, 200, 10, 39, 100, -5, 0) - val oddAndSmallPartial: PartialFunction[Int, String] = { - case x: Int if x % 2 != 0 && x < 100 ⇒ "Odd and less than 100" + val zeroPartial: PartialFunction[Int, String] = { + case x: Int if x == 0 ⇒ "Zero" } - val evenAndSmallPartial: PartialFunction[Int, String] = { - case x: Int if x != 0 && x % 2 == 0 && x < 100 ⇒ "Even and less than 100" + val largePartial: PartialFunction[Int, String] = { + case x: Int if x > 99 ⇒ "Large Number" } val negativePartial: PartialFunction[Int, String] = { case x: Int if x < 0 ⇒ "Negative Number" } - val largePartial: PartialFunction[Int, String] = { - case x: Int if x > 99 ⇒ "Large Number" + val oddPartial: PartialFunction[Int, String] = { + case x: Int if x % 2 != 0 ⇒ "Odd" } - val zeroPartial: PartialFunction[Int, String] = { - case x: Int if x == 0 ⇒ "Zero" + val evenPartial: PartialFunction[Int, String] = { + case x: Int if x % 2 == 0 ⇒ "Even" } val result = array groupBy { - oddAndSmallPartial orElse - evenAndSmallPartial orElse - negativePartial orElse - largePartial orElse - zeroPartial + zeroPartial orElse + largePartial orElse + negativePartial orElse + oddPartial orElse + evenPartial } - (result("Even and less than 100") size) should be(res0) + (result("Zero") size) should be (res0) (result("Large Number") size) should be(res1) + (result("Negative Number") size) should be(res2) + (result("Even") size) should be(res3) } /** `forall` will determine if a predicate is valid for all members of a `Traversable`: