Reputation: 51
I am new to Scala and am trying to get to grips with Option. I am trying to sum the double values members of the following list according to their string keys:
val chmembers = List(("Db",0.1574), ("C",1.003), ("Db",15.4756), ("D",0.003), ("Bb",1.4278), ("D",13.0001))
Summing as:
List((D,13.0031), (Db,15.633000000000001), (C,1.003), (Bb,1.4278))
My current code is
def getClassWeights: List[(Option[String], Option[Double])] = {
chMembers.flatMap(p => Map(p.name -> p.weight))
.groupBy(_._1).mapValues(_.map(_._2)sum).toList
}
However this will not compile and returns:
'Could not find implicit value for parameter num: Numeric[Option[Double]]'. I don't understand where 'Numeric' comes from or how handle it.
I would be grateful for any suggestions. Thanks in advance.
Upvotes: 1
Views: 2531
Reputation: 34393
Numeric is used to perform the sum
. It is a type class which implements some common numeric operations for Int
, Float
, Double
etc.
I am not sure why you want to use Option
, I do not think it will help you solving your problem. Your code can be simplified to:
val chmembers = List(("Db",0.1574), ("C",1.003), ("Db",15.4756), ("D",0.003), ("Bb",1.4278), ("D",13.0001))
def getClassWeights: List[(String, Double)] = {
chmembers.groupBy(_._1).mapValues(_.map(_._2).sum).toList
}
Upvotes: 1
Reputation: 2686
you can do it like this:
val chmembers = List(("Db",0.1574), ("C",1.003), ("Db",15.4756), ("D",0.003), ("Bb",1.4278), ("D",13.0001))
chmembers.groupBy(_._1).mapValues(_.map(_._2).sum)
output
//Map(D -> 13.0031, Db -> 15.633000000000001, C -> 1.003, Bb -> 1.4278)
Upvotes: 0