我有一個書單:Scala的for循環高階函數
case class Book(name:String,authors:List[String])
val books:List[Book] = List(
Book(name="Code in Scala",authors=List("Viny","Vinay")),
Book(name="Dance in 30 days",authors=List("Namratha","Namitha")),
Book(name="Cook in 30 days",authors=List("Pavan")),
Book(name="Gym in 30 days",authors=List("Nisanth","Vinay"))
)
現在我想知道作者的名字與「輸入電壓」開頭的書籍。 我已經實現了這個for循環象下面這樣:
for(b<-books ; a <- b.authors ; if a.startsWith("Vin")) yield b.name
,但我無法用高階函數來實現這一點。 我試過如下:
books flatMap (b=> b.authors.withFilter(a=>a.startsWith("Vin")).map(x=>x))
這讓我對作者的姓名,但我無法訪問我的書object.how解決這個問題?這裏 主要目標是轉換/翻譯了「循環」到高階函數(flatmap /過濾/圖)
如果你想從第二個代碼示例,你會得到書對象中刪除name屬性。你能用高階函數來展示你的代碼嗎? – Pavel