2017-07-04 49 views
1

对于2D列表/数组的每个元素都可以使用“foreach”吗? 我试过代码:scala foreach of 2-D List/Array in chisel with types issue

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

错误消息是

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

你能ENLIGHT我是否能以这样的方式被使用,甚至如何?

+0

它看起来像你的代码是期待一个类型UInt'的',而是一个'foreach'的返回类型将永远是一个'Unit',试图改变'foreach'到'map' – Tyler

+0

@泰勒是的,我知道'地图'可以做到这一点。但不知何故,它返回数组/列表花费更多的内存,也知道'for' body可以做到这一点。我只是想知道“foreach”会引导我学习它。 –

+0

@Tyler问题是参数类型,而不是返回类型。 –

回答

4

这将是清洁剂这样写:

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

但你并不需要手动增加xy,只是遍历指数来代替:

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

或更好(并且这完全转换为ab OVE)

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

是的,它可以这样使用。

解决方案:

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