简体   繁体   中英

scala reduce a complex structure

I have the following case classes

case class AdsWeight(ads: Seq[LimitedAd], finalWeight: Double)

case class LimitedAd(
    id: Long,
    tid: Long,
    mt: String,
    oe: String,
    bid: Double,
    score: Double,
    ts: Double
)

Now given val records: Seq[AdsWeight] , how can I replace the score s in every LimitedAd with score * finalWeight , and then concat only the LimitedAd to output?

Eg,

val ad1 = LimitedAd(1, 100, "mt1", "ot1", 0.1, 0.01, 0.001)
val ad2 = LimitedAd(2, 200, "mt2", "ot2", 0.2, 0.02, 0.002)
val ad3 = LimitedAd(3, 300, "mt3", "ot4", 0.3, 0.03, 0.003)
val ad4 = LimitedAd(4, 400, "mt4", "ot4", 0.4, 0.04, 0.004)

val ads1 = AdsWeight(Seq(ad1, ad2), 0.9)
val ads2 = AdsWeight(Seq(ad3, ad4), 0.8)

val records: Seq[AdsWeight] = Seq(ads1, ads2)

and get the output

[
(1, 100, "mt1", "ot1", 0.1, 0.009, 0.001), (2, 200, "mt2", "ot2", 0.2, 0.018, 0.002)
(3, 300, "mt3", "ot3", 0.3, 0.024, 0.003), (4, 400, "mt4", "ot4", 0.4, 0.032, 0.004)
]
scala> val res =  records.flatMap(r => r.ads.map(ad => ad.copy(score = ad.score * r.finalWeight)))
val res: Seq[LimitedAd] = List(LimitedAd(1,100,mt1,ot1,0.1,0.009000000000000001,0.001), LimitedAd(2,200,mt2,ot2,0.2,0.018000000000000002,0.002), LimitedAd(3,300,mt3,ot4,0.3,0.024,0.003), LimitedAd(4,400,mt4,ot4,0.4,0.032,0.004))

scala> res.foreach(println)
LimitedAd(1,100,mt1,ot1,0.1,0.009000000000000001,0.001)
LimitedAd(2,200,mt2,ot2,0.2,0.018000000000000002,0.002)
LimitedAd(3,300,mt3,ot4,0.3,0.024,0.003)
LimitedAd(4,400,mt4,ot4,0.4,0.032,0.004)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM