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我正在尝试一个问题来获得的平均书名长度,是以年份写成的偶数的书籍。
在这种情况下,我希望能够确定4,而不是硬编码,并且不需要在内存中使用第二个值。
有没有办法说“这个”或“先前”之类的词来指当前(过滤)列表的长度--试图在谷歌上搜索,但我很难用这个词来表达对搜索引擎的查询。
事先非常感谢
发布于 2016-12-30 17:03:51
如何将foldLeft与match结合使用?也许有点复杂,但您可以使用foldLeft生成一对,第一个值是列表的和,第二个值是列表长度的计数器,然后使用match计算平均值(除以长度):
(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.25https://stackoverflow.com/questions/41399736
复制相似问题