5
\$\begingroup\$

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)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ The forall solution seems like the optimal solution to me. \$\endgroup\$
    – RoToRa
    Jul 27, 2011 at 14:04

2 Answers 2

5
\$\begingroup\$

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?

\$\endgroup\$
0
4
\$\begingroup\$

I've come up with an alternative, which is nice and compact:

val teamSizes = teams.map(_.members.size)
require(teamSizes.forall(_ == teamSizes.head))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.