Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revising Traversables.scala groupBy example #128

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions src/main/scala/stdlib/Traversables.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down