user2466860 - 9 months ago 72

Scala Question

I have a vector of 4 bits, where I want to check if a single bit from the vector from the vector is a 1. So, basically I want to have loop with 4 iterations, where the first iteration will check if the first bit from the vector is a 1, and then in the next iteration check if the second bit is a 1 and so on.

I have tried with a switch statement shown below, but it doesn't work like I want it to.

`for(i <- 0 until ways) { //ways = 3`

switch(current_way(i)){

is(UInt(1)){

way_dout(i) := way.io.dout((i+1)*line_size-1,i*line_size)

}

}

Thank you in advance.

Answer Source

FYI, to help us give you the best answers, you should show us your instantiations of your variables (i.e., what type is current_way, way_dout, and ways?).

There are a number of approaches here. One idea is this:

```
val ways_vector = Wire(Vec(num_ways, Bool())
val way_dout = Wire(init=Vec.fill(num_ways){UInt(0, width = line_size)})
...
// set values of ways_vector...
...
for (i <- 0 until num_ways) {
when (ways_vector(i)) {
...
}
}
```

But `for`

loops are ugly. Maps show your intent more clearly:

```
val way_dout =
ways_vector.zipWithIndex.map{ case (w, i) =>
Mux(w,
way.io.dout((i+1)*line_size-1, i*line_size),
UInt(0))}
```

`zipWithIndex`

is a scala-ism, and it brings a lot of awesome power to hardware design.