【发布时间】:2011-05-19 05:00:11
【问题描述】:
我正在寻找一种将产品分配给数字类型数组的快速方法。例如,我想用 values 填充 array 元素:
// not restricted to be 4-by-2, can be abritary
// Double will be later replaced by type T : Numeric
var elements = new Array[Double](4*2)
// can contain other Numemrics as Int
var values = ((11.0,12.0),(21.0,22.0),(31.0,32.0), (4.0,1.0))
到目前为止我的方法是
var i = 0;
var itRow = values.productIterator.asInstanceOf[Iterator[Product]]
while(itRow.hasNext){
var itCol = itRow.next.productIterator.asInstanceOf[Iterator[Double]]
while(itCol.hasNext){
elements(i) = itCol.next.asInstanceOf[Double]
i = i + 1
}
}
如果值中的所有条目都是 Double,则它可以工作,但如果它也适用于 abritary Numerics,那就太好了。 其次,有没有更优雅、更快捷的方法来做到这一点?也许将元组扁平化会更好
def flatProduct(t: Product): Iterator[Any] = t.productIterator.flatMap {
case p: Product => flatProduct(p)
case x => Iterator(x)
}
// edit: I think this is better,
// but still the problematic if there are Int-types in values
flatProduct(values).asInstanceOf[Iterator[Dobule]].copyToArray(elements)
你怎么看?
非常感谢!
【问题讨论】:
标签: scala