HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Checking a collection of Ints

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkingcollectionints

Problem

I'm learning a little Scala by writing a little card game. What I want to do here is check that the Traversable[Team] supplied has the same number of team members for each team.

How can I clean this up?

val teamSizes = teams.map(_.members.size)
require(teamSizes.foldLeft((true, teamSizes.head)) {
  (tuple, lastSize) =>
    val (b, size) = tuple
    (b && size == lastSize, lastSize)
}._1)

Solution

An alternative approach is:

require (teamSizes.min == teamSizes.max)


but ỳour forall-solution expresses better the idea, that all members share the same size.

And without measuring it, or trying to investigate my assumption, I guess that my approach traverses the collection twice, which could be a drawback for bigger collections or if performed million of times. So less so in this example.

But maybe it is possible to model the constraint into your design, so that all teams get the right size from the beginning?

Code Snippets

require (teamSizes.min == teamSizes.max)

Context

StackExchange Code Review Q#3651, answer score: 5

Revisions (0)

No revisions yet.