Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional computation of list-values

I have 2 Lists containing lottery-ticket instances.

One List holds tickets that won a special prize, the other List contains Tickets that got final-digit-hits.

Now I have to eliminate those tickets with redundant numbers and add the prizes together.

case class Ticket(number:Long, prize:Long)

val specialPrizes    = List(Ticket(42, 1000), Ticket(66, 2000))
val finalDigitPrizes = List(Ticket(42, 50))

This would yield a List with merged Tickets which themselves contain accumulated prizes:

val finalList = List(Ticket(42, 1050), Ticket(66, 2000))

What would be the most effective way to do this functionally without temp-vars, index-counters, etc?

like image 738
recalcitrant Avatar asked Jan 17 '23 12:01

recalcitrant


1 Answers

scala> (specialPrizes ++ finalDigitPrizes).groupBy(_.number).map {
     |   case (n, ts) => Ticket(n, ts.map(_.prize).sum)
     | }
res1: scala.collection.immutable.Iterable[Ticket] = List(Ticket(42,1050), Ticket(66,2000))
like image 137
retronym Avatar answered Jan 23 '23 05:01

retronym