1
votes

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.

2
Why do you want to return Option[_]? What condition should create a None value?jwvh

2 Answers

1
votes

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
}
0
votes

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)