Scala / Lists - any way to refer to current filtered list to get size of current (not size of original)

51 views Asked by At
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

1

There are 1 answers

2
Psidom On BEST ANSWER

How about using foldLeft with match? Maybe a little bit convoluted but you can use foldLeft 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 use match to calculate the average (dividing the sum by the length):

(books.filter{x => x.year % 2 == 0}
      .map(_.title.length)
      .foldLeft((0, 0))((x, y) => (x._1 + y, x._2 + 1)) 
      match { case(x,y) => x.toDouble/y})

# res73: Double = 35.25