简体   繁体   English

带有类型问题的凿子中二维列表/数组的scala foreach

[英]scala foreach of a 2-D List/Array in chisel with types issue

Can "foreach" can be used for each element of the 2-D List/Array? 可以将“ foreach”用于二维列表/数组的每个元素吗? I tried the code: 我尝试了代码:

val n_vec = (0 to 2).map(i=>
              (0 to 2).map(j=>
                Wire(UInt(3.W))
              )
            ) 
n_vec.foreach((i:Int)=>(
  n_vec(i).foreach((j:Int)=>{
    n_vec(i)(j) := i.U + j.U
  })
))

the error message is 错误消息是

top.scala:24: error: type mismatch;
 found   : Int => Unit
 required: chisel3.core.UInt => ?
      n_vec(i).foreach((j:Int)=>{
                              ^

Could you enlight me whether it can be used in such a way, even how? 您能否启迪我是否可以这种方式使用它,甚至如何使用?

It would be cleaner to write like this: 这样写会更干净:

n_vec.foreach { i=>
  i.foreach { j=>
    j := x.U + y.U
    y = y + 1
  }
  y = 0
  x = x + 1
}

But you don't need to increment x and y manually, just iterate over indices instead: 但是您不需要手动增加xy ,而只需遍历索引即可:

n_vec.indices.foreach { x =>
  n_vec(x).indices.foreach { y =>
    n_vec(x)(y) := x.U + y.U
  }
}

or better (and this translates exactly to the above) 或更好(这与上面的意思完全一样)

for { 
  x <- n_vec.indices
  y <- n_vec(x).indices
} {
  n_vec(x)(y) := x.U + y.U
}

Yes it can be used this way. 是的,可以通过这种方式使用。

solution: 解:

var x = 0
var y = 0 
n_vec.foreach(i=>{
  i.foreach(j=>{
    j := x.U + y.U
    y = y + 1
  })
  y = 0
  x = x + 1
})
x = 0
y = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM