tags:

views:

180

answers:

2

Assume I have a routine which takes an enumeration value as an argument and returns a Boolean ... and I want to check a set of those enumeration values to see if they are all true. Is there a idiomatic way to do it. This was my "old school" attempt which seems non-scala-ish:

def allUnitQueuesEmpty(): Boolean =
    ( getQueue(QID.CPU).isEmpty() &&
      getQueue(QID.L1C_I).isEmpty() &&
      getQueue(QID.L1D_I).isEmpty() &&
      getQueue(QID.L1VC_I).isEmpty() &&
      getQueue(QID.L1C_D).isEmpty() &&
      getQueue(QID.L1D_D).isEmpty() &&
      getQueue(QID.L1VC_D).isEmpty() &&
      getQueue(QID.L1WB_D).isEmpty() &&
      getQueue(QID.L2C).isEmpty() &&
      getQueue(QID.L2WB).isEmpty() &&
      getQueue(QID.MEM_RD).isEmpty() &&
      getQueue(QID.MEM_WRT).isEmpty() );

Can this be done with a List?

-Jay

+5  A: 

All of Scala's collections have forall and exists methods which ascertain whether the collection to which they're applied satisfies the predicate supplied as an argument (over the elements of the collection) for every element (forall) or for at least one element (exists).

Randall Schulz
+22  A: 

No need for a list, actually. QID.values() returns an array of all QID values, and an array can be implicitly converted to a Scala collection, which allows you to define

def allUnitQueuesEmpty(): Boolean = QID.values.forall(v => getQueue(v).isEmpty)

If you only needed some of those values, this would work instead:

import QID._
def l1UnitQueuesEmpty(): Boolean = Array(L1C_I, L1D_I, L1VC_I).forall(v => getQueue(v).isEmpty)
Alexey Romanov