Domanda

I've a class

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

I've a list of PlaceHolder objects and I want to create one object which contains the sum of all the values of field a and b. I don't care about time. I believe it can be done with fold/reduce operations but cannot figure how to do it with two fields.

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))
È stato utile?

Soluzione

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

or

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

or you could add a + operator to 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)
}

then you can do:

placeholders.reduce(_ + _)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top