Coursera Scala 2-1:高阶函数

本文介绍了如何使用Scala中的高阶函数来避免重复代码,并通过具体的文件处理案例展示了高阶函数的强大之处,包括如何利用闭包和占位符进一步简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把函数当做参数,传递给函数(好绕-..-),称为高阶函数。
高阶函数使我们的代码保持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章,控制抽象



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值