2016-12-30 21 views
0
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而不是硬編碼它,而不使用內存中的第二個值。

有沒有什麼方法可以說'this'或'previous'是指當前(過濾)列表的長度 - 試圖谷歌這個,但我很努力短語搜索引擎的查詢。

提前

+0

在求和之前將它賦值爲 –

+0

當然,如果我想浪費內存,我可以這樣做。 :-) – TheDavil

+1

認真嗎? 4字節? –

回答

3

非常感謝如何使用foldLeftmatch?也許有點複雜,但你可以使用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.25 
+0

看起來不錯,我想我現在看到使用累加器等等。我只需要把我的腦袋充分的圍繞這個如何工作(我是一個scala n00b)。謝謝! – TheDavil

+0

爲了我的理智,我要記住我的考試(效率低下版本): books.filter {x => x.year%2 == 0} .map(x => x.title.length) .sum/books.count {x => x.year%2 == 0}但是,您的版本更優雅,再次感謝。 – TheDavil