【问题标题】:Assign nested Product/Tuple to Array[Numeric]将嵌套的 Product/Tuple 分配给 Array[Numeric]
【发布时间】: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


    【解决方案1】:

    任你选:

    scala> values.productIterator.map{case (x: Double, y: Double) => Array(x, y)}.flatten.toList
    res17: List[Double] = List(11.0, 12.0, 21.0, 22.0, 31.0, 32.0, 4.0, 1.0)
    
    scala> values.productIterator.asInstanceOf[Iterator[(Double,Double)]].foldLeft(List[Double]()){(l, i) => i._2 :: i._1 :: l}.reverse
    res18: List[Double] = List(11.0, 12.0, 21.0, 22.0, 31.0, 32.0, 4.0, 1.0)
    
    scala> values.productIterator.foreach{var i = 0; {case (x: Double, y: Double) => elements(i) = x; elements(i + 1) = y; i += 2}}
    
    scala> elements
    res19: Array[Double] = Array(11.0, 12.0, 21.0, 22.0, 31.0, 32.0, 4.0, 1.0)
    

    【讨论】:

    • 感谢您的快速答复!对不起,我的描述不够清楚。问题是,元组不限于 4×2,也不限于 Double(但数组是 Double)
    • 在这种情况下,您的 flatProduct 方法很好。只需在调用后添加.map(convert).toArray,其中convert 是一个函数Any => Double。由于它是一个迭代器,所以一切都是一次完成(转换为数组时)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多