Coursera Scala 2-1:高階函數
把函數當做參數,傳遞給函數(好繞-..-),稱為高階函數。
高階函數使我們的代碼保持DRY(Dont't Repeat Yourself)
舉個例子
一個返回所有擴展名為".scala"的文件的方法:
def filesHere = (new java.io.File(".")).listFiles
def filesEnding(query: String) =
for (file <- filesHere; if file.getName.endsWith(query))
yield file
}
如果我們需要一個方法,返回所有包含特定關鍵字的文件:
def filesContaining(query: String) =
for (file <- filesHere; if file.getName.contains(query))
yield file
如果我們又需要一個方法,返回所有匹配通配符的文件:
def filesRegex(query: String) =
for (file <- filesHere; if file.getName.matches(query))
yield file
很明顯,這裏有很多重複的代碼。使用高階函數,我們將對文件名處理的地方用傳遞進來的函數處理:
def filesMatching(query: String,
matcher: (String, String) => Boolean) = {
for (file <- filesHere; if matcher(file.getName, query))
yield file
}
使用閉包
(包含自由變量,函數文本參數沒有該變量,但是函數文本內有該變量,通過捕獲得到。稱為閉包)和占位符
進一步簡化代碼:
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere; if matcher(file.getName))
yield file
def filesEnding(query: String) =
filesMatching(_.endsWith(query))
def filesContaining(query: String) =
filesMatching(_.contains(query))
def filesRegex(query: String) =
filesMatching(_.matches(query))
Reference
Scala編程第9章,控製抽象
最後更新:2017-04-03 12:56:38