Scala函数式编程入门:高阶函数与多态函数
立即解锁
发布时间: 2025-08-18 01:01:37 阅读量: 1 订阅数: 5 

### Scala函数式编程入门:高阶函数与多态函数
#### 1. 编写第一个高阶函数
在编程中,我们常常会遇到一些功能相似的函数。例如,有两个函数`formatAbs`和`formatFactorial`:
```scala
private def formatAbs(x: Int) = {
val msg = "The absolute value of %d is %d."
msg.format(x, abs(x))
}
private def formatFactorial(n: Int) = {
val msg = "The factorial of %d is %d."
msg.format(n, factorial(n))
}
```
这两个函数的结构非常相似,我们可以将它们泛化为一个高阶函数`formatResult`:
```scala
def formatResult(name: String, n: Int, f: Int => Int) = {
val msg = "The %s of %d is %d."
msg.format(name, n, f(n))
}
```
`formatResult`函数接受一个字符串`name`、一个整数`n`和一个函数`f`作为参数。这里的`f`是一个从`Int`到`Int`的函数。我们可以将`abs`或`factorial`作为`f`参数传递给`formatResult`:
```scala
scala> formatResult("absolute value", -42, abs)
val res0: String = "The absolute value of -42 is 42."
scala> formatResult("factorial", 7, factorial)
val res1: String = "The factorial of 7 is 5040."
```
在高阶函数中,通常使用像`f`、`g`和`h`这样的短变量名作为参数名,这是一种常见的约定。
#### 2. 多态函数:类型抽象
到目前为止,我们定义的函数大多是单态函数,即只对一种类型的数据进行操作。例如,`abs`和`factorial`函数只适用于`Int`类型的参数,高阶函数`formatResult`也只能处理接受`Int`类型参数的函数。而多态函数则可以对多种类型的数据进行操作。
##### 2.1 多态函数示例
以`findFirst`函数为例,最初它是一个单态函数,用于在`String`数组中查找某个`String`的第一个索引:
```scala
def findFirst(ss: Array[String], key: String): Int = {
@annotation.tailrec
def loop(n: Int): Int = {
if n >= ss.length then -1
else if ss(n) == key then n
else loop(n + 1)
}
loop(0)
}
```
我们可以将其改写为多态函数,使其适用于任何类型`A`的数组:
```scala
def findFirst[A](as: Array[A], p: A => Boolean): Int = {
@annotation.tailrec
def loop(n: Int): Int = {
if n >= as.length then -1
else if p(as(n)) then n
else loop(n + 1)
}
loop(0)
}
```
在这个多态版本中,我们使用了类型参数`[A]`,并接受一个函数`p`来测试数组中的元素。
##### 2.2 使用匿名函数调用高阶函数
在使用高阶函数时,
0
0
复制全文
相关推荐










