开发者

Scala way to change this into a list?

开发者 https://www.devze.com 2023-01-12 10:20 出处:网络
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

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 t开发者_如何学Gohis be done with a List?

-Jay


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消