2
我正在寻找一种将产品分配给数字类型为数组的快速方法。比如我要填补阵列元素与值:将嵌套的产品/元组分配给数组[数字]
// 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
}
}
它的工作原理如果值的所有条目是双,但它会很高兴让这个工作对于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)
你觉得怎么样?
非常感谢!
感谢您的快速答复!对不起,我的描述不够清楚。在这种情况下,该元组不限于4×2,并且不限于Double(但是Array是Double) – Markus 2011-05-19 06:43:07
,在这种情况下,您的flatProduct方法是很好的。只需在调用它之后添加'.map(convert).toArray',其中'convert'是一个函数'Any => Double'。由于它是一个迭代器,所有事情都是一次完成的(当转换为数组时) – IttayD 2011-05-19 08:54:25