case class Book(title: String, authors: List[String], year: Int)
val books: List[Book] = List(
Book("Structure and Interpretation of Computer Programs",
List("Abelson, Harold", "Sussman, Gerald J."), 1984),
Book("Principles of Compiler Design",
List("Aho, Alfred", "Ullman, Jeffrey"), 1977),
Book("Programming in Modula-2",
List("Wirth, Niklaus"), 1982),
Book("Introduction to Functional Programming",
List("Bird, Richard"), 1988),
Book("The Java Language Specification",
List("Gosling, James", "Joy, Bill", "Steele, Guy",
"Bracha, Gilad"), 1996)
)
books.filter{x => x.year % 2 == 0}
.map(_.title.length)
.sum / 4.toDouble
I'm attempting a problem to get average length of titles for books written in years that are even numbers.
In this case I want to be able to determine the 4 rather than hardcoding it, and without using a second value in memory.
is there any way to say something like 'this' or 'previous' to refer to the length of the current (filtered) list - tried to google this but I'm struggling to phrase the query for a search engine.
Many thanks in advance
How about using
foldLeft
withmatch
? Maybe a little bit convoluted but you can usefoldLeft
to generate a pair with the first value be the sum of the list and the second value be a counter of the length of the list and then usematch
to calculate the average (dividing the sum by the length):