Search code examples
scalareducechisel

Is it good thing to use `reduce(_ ## _) ` for IndexedSeq to UInt conversion in Chisel?


For a little Chisel project I'm using reduce(_ ## _) function to convert an IndexedSeq to UInt.

class PdChain(n: Int = 4) extends Module {
  val io = IO(new Bundle {
    val count = Output(UInt(n.W))
  })
  // instantiate PdivTwo modules
  val pDivTwo = for (i <- 0 until n) yield {
    val pdivtwo = Module(new PDivTwo(i == 0))
    pdivtwo
  }
  val pDivTwo_io = VecInit(pDivTwo.map(_.io))

  // connect together
  pDivTwo_io(0).en := 1.U(1.W)
  for(i <- 1 until n) {
    pDivTwo_io(i).en := pDivTwo_io(i-1).p
  }

  val countValue = for (i <- 0 until n) yield pDivTwo_io(i).q

  io.count := countValue.reverse.reduce(_ ## _)
}

The value countValue is seen as IndexedSeq and reduce() operation convert it to UInt.

That works without error in my project. But I read that reduce() function must be used on commutative operations.

Concatenation ## operator is not commutative, then should avoid it here ?


Solution

  • Thanks to Seth-Tisue I have the answer : Yes I should avoid reduce().

    In this case, reduceLeft() should be used.