Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Scala syntax for summing a List of objects?

Tags:

For example

case class Blah(security: String, price: Double) val myList = List(Blah("a", 2.0), Blah("b", 4.0)) val sum = myList.sum(_.price) // does not work 

What is the syntax for obtaining the sum?

like image 547
deltanovember Avatar asked Sep 28 '11 04:09

deltanovember


People also ask

How do you sum a list in Scala?

Scala List sum() method with example. The sum() method is utilized to add all the elements of the stated list. Return Type: It returns the sum of all the elements of the list.

How do you define a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.


2 Answers

Try this:

val sum = myList.map(_.price).sum 

Or alternately:

val sum = myList.foldLeft(0.0)(_ + _.price) 

You appear to be trying to use this method:

def sum [B >: A] (implicit num: Numeric[B]): B 

and the compiler can't figure out how the function you're providing is an instance of Numeric, because it isn't.

like image 144
Tom Crockett Avatar answered Oct 26 '22 04:10

Tom Crockett


Scalaz has this method under a name foldMap. The signature is:

def M[A].foldMap[B](f: A => B)(implicit f: Foldable[M], m: Monoid[B]): B 

Usage:

scala> case class Blah(security: String, price: Double) defined class Blah  scala> val myList = List(Blah("a", 2.0), Blah("b", 4.0)) myList: List[Blah] = List(Blah(a,2.0), Blah(b,4.0))  scala> myList.foldMap(_.price) res11: Double = 6.0 

B here doesn't have to be a numeric type. It can be any monoid. Example:

scala> myList.foldMap(_.security) res12: String = ab 
like image 30
missingfaktor Avatar answered Oct 26 '22 04:10

missingfaktor