如何在scala中使用fold / reduce来实现这一点?

时间:2014-04-14 20:51:01

标签: scala reduce fold

我有一个班级

case class PlaceHolder(time: Long, a: Int, b: Int) 

我有PlaceHolder个对象的列表,我想创建一个对象,其中包含字段ab的所有值的总和。我不关心time。我相信它可以通过折叠/缩小操作来完成,但无法用两个字段来计算它是如何做到的。

scala> val range = 1 to 10
range: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val placeholders = for{ i <- range} yield PlaceHolder(i,i,i) 
placeholders: scala.collection.immutable.IndexedSeq[PlaceHolder] = Vector(PlaceHolder(1,1,1), PlaceHolder(2,2,2), PlaceHolder(3,3,3), PlaceHolder(4,4,4), PlaceHolder(5,5,5), PlaceHolder(6,6,6), PlaceHolder(7,7,7), PlaceHolder(8,8,8), PlaceHolder(9,9,9), PlaceHolder(10,10,10))

1 个答案:

答案 0 :(得分:5)

placeholders.foldLeft(PlaceHolder(0,0,0))((acc, p) => PlaceHolder(acc.time + p.time, acc.a + p.a, acc.b + p.b))

placeholders.reduce((acc, p) => PlaceHolder(acc.time + p.time, acc.a + p.a, acc.b + p.b))

或者您可以向+添加PlaceHolder运算符:

case class PlaceHolder(time: Long, a: Int, b: Int) {
    def +(other: PlaceHolder) = PlaceHolder(this.time + other.time, this.a + other.a, this.b + other.b)
}

然后你可以这样做:

placeholders.reduce(_ + _)