Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala way to change this into a list?

Tags:

scala

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

like image 991
jayped007 Avatar asked Aug 22 '10 21:08

jayped007


2 Answers

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)
like image 96
Alexey Romanov Avatar answered Sep 27 '22 21:09

Alexey Romanov


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).

like image 36
Randall Schulz Avatar answered Sep 27 '22 21:09

Randall Schulz