Consider this class:
case class Person(val firstName: String, val lastName: String, age: Int)
val persons = Person("Jane", "Doe", 42) :: Person("John", "Doe", 45) ::
Person("Joe", "Doe", 43) :: Person("Doug", "Don", 65) ::
Person("Darius", "Don", 24) :: Person("Dora", "Don", 20) ::
Person("Dane", "Dons", 29) :: Nil
To get the sum of the age of all persons, I can write code like:
persons.foldLeft(0)(_ + _.age)
But if I want to use sum
, I need to map the value first and the code looks like this:
persons.map(_.age).sum
How can I use the sum
method without creating some intermediate collection?
(I know that such an "optimization" most probably doesn't have any real performance difference when not run in a tight loop and I also know about lazy views and so on.)
Is it possible to have code like
persons.sum(_.age)
doing what foldLeft
/reduceLeft
does?
sumBy
(cf.sortBy
) would be a reasonable extension for the collection library. – CarouseprodOf
andmaxOf
andminOf
. And then those of us who like median or mean or entropy or (etc.) will feel left out. A good oldmapReduce
might be nice. But beyond that I think it's better for all involved to get used to folding and/or views. – HostelmaxBy
andminBy
! That's the point I am making here. – Bytefilter
,flatten
andmap
, because those are just some "convenenience" method. – Byte