Programming in Scala (Second Edition) 读书笔记6 函数和闭包

When programs get larger, you need some way to divide them into smaller,

more manageable pieces. For dividing up control flow, Scala offers an approach familiar to all experienced programmers: divide the code into functions. In fact, Scala offers several ways to define functions that are not

present in Java. Besides methods, which are functions that are members

of some object, there are also functions nested within functions, function literals, and function values. This chapter takes you on a tour through all of

these flavors of functions in Scala

大而化之的编程思想

多种多样的方法创建函数


1. The most common way to define a function is as a member of some object.

Such a function is called a method

通过在对象内部定义方法来定义函数


2. 在函数的body中定义函数,即本地函数(local function)

you can define functions inside other functions. Just like local variables, such local functions are visible only in their enclosing block

本地函数只在它所在的函数闭包内可见


3.匿名函数, 或者叫做函数字面值

val cubic = (x:Int) => x * x * x


4.忽略参数类型

	val nums = List(1,2,3,4,5)                //> nums  : List[Int] = List(1, 2, 3, 4, 5)
	nums.filter((x) => x > 2)                 //> res0: List[Int] = List(3, 4, 5)

5.使用placeholder继续简化

	val nums = List(1,2,3,4,5)                //> nums  : List[Int] = List(1, 2, 3, 4, 5)
	nums.filter(_ > 2)                        //> res0: List[Int] = List(3, 4, 5)
	val f = (_: Int) + (_: Int)               //> f  : (Int, Int) => Int = <function2>


6.偏函数 (patially applied functions)

考虑这样一个场景:已经定义了一个函数f,它接受5个参数。使用的时候发现有2个参数总是固定的。那么有没有一个简单的方法,定义一个与f功能相同的函数,但是只接受3个参数.

  def sum5(a: Int, b: Int, c: Int, d: Int, e:Int) = a + b + c + d +e
                                                  //> sum5: (a: Int, b: Int, c: Int, d: Int, e: Int)Int
  val sum3 = sum5(_: Int, 2, _: Int, 3,_: Int)    //> sum3  : (Int, Int, Int) => Int = <function3>


7.定义和调用一个函数的特殊方式(special function call forms)

不定参,默认值,具名参数等于python类似


8.尾递归

    def approximate(guess: Double): Double =
      if (isGoodEnough(guess)) guess
      else approximate(improve(guess))

 Note that the recursive call is the last

thing that happens in the evaluation of function approximate’s body. Functions like approximate, which call themselves as their last action, are called

tail recursive. The Scala compiler detects tail recursion and replaces it with

a jump back to the beginning of the function, after updating the function

parameters with the new values.


因此scala中的尾递归可以达到和循环语句几乎同样的效率

你可能感兴趣的:(scala)