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中的尾递归可以达到和循环语句几乎同样的效率

时间: 2024-10-05 18:33:57

Programming in Scala (Second Edition) 读书笔记6 函数和闭包的相关文章

Programming in Scala (Second Edition) 读书笔记21 隐式转化

1. There's a fundamental difference between your own code and libraries of other people: you can change or extend your own code as you wish, but if you want to use someone else's libraries, you usually have to take them as they are. 你可以改变或扩展自己的代码,但是对

Programming in Scala (Second Edition) 读书笔记13 packages and import

目前,在一个包中你看到的top level的对象只有:class, trait, object.其实任何对象都可以是top level的.也就是说,没有必要把函数,value, variable等限制在class, trait, object中.它们可以在整个包范围内都是全局性的. 方法很简单,把这些东东放到package object中就行了.pakcage object的名字和包名相同 包含package object的文件放在该packag下,名字就叫package.scala chapt

Programming in Scala (Second Edition) 读书笔记12 Trais

1.什么是Trait ? Traits are a fundamental unit of code reuse in Scala. A trait encapsulatesmethod and field definitions, which can then be reused by mixing them intoclasses. Unlike class inheritance, in which each class must inherit from justone supercla

Programming in Scala (Second Edition) 读书笔记15 case class and pattern matching

一个算术表达式包含: 数字,变量,二元操作符,一元操作符.用下面几个类来模拟它们 package chapter15 abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: 

Programming in Scala (Second Edition) 读书笔记10

你肯定见过在控制台用字符打印图形的程序,这一章就从定义一个图形元素开始.我们的图形元素都是一些字符组成的矩形 abstract class Element {   def contents: Array[String]   def height: Int = contents.length   def width: Int = if (height == 0) 0 else contents(0).length } 上面定义的三个方法都没有参数,连小括号也省去了.这样的方法叫做:无参方法(par

Programming in Scala (Second Edition) 读书笔记7 内置控制结构

1. One thing you will notice is that almost all of Scala's control structures result in some value Scala的每种控制语句都是有值的 This is the approach taken by functional languages, in which programs are viewed as computing a value, thus the components of a progr

Programming in Scala (Second Edition) 读书笔记26 Extractors

1. By now you have probably grown accustomed to the concise way data can be decomposed and analyzed using pattern matching. This chapter shows you how to generalize this concept further. Until now, constructor patterns were linked to case classes. Fo

Programming in Scala (Second Edition) 读书笔记3

创建并初始化一个String Array     val strArr1 = new Array[String](3)     strArr1(0) = "How"     strArr1(1) = "are"     strArr1(2) = "you!" 上述代码被transform 为     val strArr1 = new Array[String](3)     strArr1.update(0, "How")

Programming in Scala (Second Edition) 读书笔记4

1.Tuple和List一样都是不可变对象(immutalbe),但是Tuple的元素可以是不同的类型     val myTuple = ("A", 1, "park", 3.13359 )     println(myTuple._1 )  // A     println(myTuple._2)  // 1     println(myTuple._3)  // park 创建Tuple只需把元素放在括号里面就可以了,上面创建了一个Tuple4类的实例,Tup