# 【Scala】高阶函数和柯里化

## 高阶函数

``````- 接受一个或多个函数作为输入
- 输出一个函数
``````

## 高阶函数的例子

``````def sumInts(a: Int, b: Int): Int =
if(a > b) 0 else a + sumInts(a + 1, b)
``````

``````def square(x: Int): Int = x * x
def sumSquares(a: Int, b: Int): Int =
if(a > b) 0 else square(a) + sumSquares(a + 1, b)
``````

``````def powerOfTwo(x: Int): Int = if(x == 0) 1 else 2 * powerOfTwo(x-1)
def sumPowersOfTwo(a: Int, b: Int): Int =
if(a > b) 0 else powerOfTwo(a) + sumPowersOfTwo(a+1, b)
``````

``````def sum(f: Int => Int, a: Int, b: Int): Int =
if(a > b) 0 else f(a) + sum(f, a+1, b)

def id(x: Int): Int = x
def square(x: Int): Int = x * x
def powerOfTwo(x: Int): Int = if(x == 0) 1 else 2 * powerOfTwo(x-1)

def sumInts(a: Int, b: Int): Int = sum(id, a, b)
def sumSquared(a: Int, b: Int): Int = sum(square, a, b)
def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b)
``````

## 有用的高阶函数

map方法将一个函数应用到某个集合的所有元素并返回结果；foreach将函数应用到每个元素。

``````//打印三角形
scala> (1 to 9).map("^" * _).foreach(println _)
^
^^
^^^
^^^^
^^^^^
^^^^^^
^^^^^^^
^^^^^^^^
^^^^^^^^^
``````

filter方法输出所有匹配某个特定条件的元素：

``````scala> (1 to 9).filter(_ % 2 == 0)
res14: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8)
``````

## 柯里化

### 返回函数的函数

``````def sum(f: Int => Int): (Int, Int) => Int = {
def sumF(a: Int, b: Int): Int =
if(a > b) 0
else f(a) + sumF(a+1, b)

sumF
}

//于是得到如下定义，这样就简化了参数
def sumInts = sum(x => x)
def sumSquared = sum(x => x * x)
def sumPowersOfTwo = sum(powerOfTwo)
``````

### 多个参数列表

``````def sum(f: Int => Int)(a: Int, b: Int): Int =
if(a > b) 0 else f(a) + sum(f)(a + 1, b)
``````