patternMinor
Checking a collection of Ints
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
How can I clean this up?
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:
but ỳour
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?
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.