Scala 函数式编程_高阶函数_Higher Order Function

Scala 函数式编程_高阶函数_Higher Order Functionhtml

高阶函数的基础就是 函数做为参数传递给另一个函数,做为参数的函数能够是匿名函数或者函数字面量,也包括用def 关键字定义的函数。java

http://my.oschina.net/xinxingegeya/blog/359335 shell

http://my.oschina.net/xinxingegeya/blog/359280 编程


什么是函数式编程

In computer science, functional programming is a programming paradigm(范式) that treats computation as the evaluation of mathematical(数学上的) functions and avoids state and mutable data.函数式编程

函数式编程是一种编程模型,他将计算机运算看作是数学中函数的计算,而且避免了状态以及变量的概念函数

能够经过下面这个连接来了解函数式编程lua

参考文章spa

http://www.cnblogs.com/kym/archive/2011/03/07/1976519.html .net

http://www.ibm.com/developerworks/cn/java/j-lo-funinscala3/scala

http://www.cnblogs.com/wzm-xu/p/4064389.html


高阶函数

什么是高阶函数?

在数学和计算机科学中,高阶函数是至少知足下列一个条件的函数:

  • 接受一个或多个函数做为输入

  • 输出一个函数


函数做为参数的高阶函数

使用高阶函数实现各类求和函数,

def cube(n: Int) = n * n * n
def id(n: Int) = n
def square(n: Int) = n * n
def fact(n: Int): Int =
  if (n == 0) 1 else n * fact(n - 1)

// 高阶函数
def sum(f: Int => Int, a: Int, b: Int): Int =
  if (a > b) 0 else f(a) + sum(f, a + 1, b)

// 使用高阶函数从新定义求和函数
def sumCube(a: Int, b: Int): Int = sum(cube, a, b)
def sumSquare(a: Int, b: Int): Int = sum(square, a, b)
def sumFact(a: Int, b: Int): Int = sum(fact, a, b)
def sumInt(a: Int, b: Int): Int = sum(id, a, b)

sumCube(1, 10)
sumInt(1, 10)
sumSquare(1, 10)
sumFact(1, 10)

sum就是一个高阶函数,由于它接收一个函数做为入参。


函数做为返回值的高阶函数

以上都是高阶函数接收一个函数参数的示例,高阶函数的返回值还能够是一个函数,那么如何定义返回函数的高阶函数,以下,

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
}


看一下在scala 的shell 中怎么表示的这种类型,以下,

scala> 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
     | }
sum: (f: Int => Int)(Int, Int) => Int

scala>

sum 的类型就是 

sum: (f: Int => Int)(Int, Int) => Int

下面来解释一下它,

f:Int=>Int 是sum函数接收的参数,该参数是一个函数。 

":" 号后面的 (Int,Int) => Int 是sum函数的返回值,又(Int,Int) => Int是一个函数的类型:接收两个Int型的数

如何调用这个函数sum,以下,

scala> sum(x=>x*x)(1,4)
res0: Int = 30

==============END==============

相关文章
相关标签/搜索