重要概念
- 纯函数(pure function)
无副作用的函数 - 函数的纯粹性(purity)
- 无副作用(side effect)
无状态mutation的变化12345678int x;public int f1(int y){return x+y;}public int f2(int y){x = x+y;return x+y;}
这里f1是无副作用,因为没有改变x的值,而f2具有副作用,改变了x的值
- 引用透明性(referential transparency)
相同的输入,总是得到相同的输出123StringBuffer x = "hello";StringBuffer y = x.append("world");StringBuffer z = x.append("world");
这里append函数不具有引用透明性,因为y和z的输出并不相同
- 不变形(immutability)
为了获得引用透明性,任何值都不会引起不变化 - 函数是一等公民first-class function
- 高阶函数high order function
- 闭包closure
- 表达式求值策略-严格求值和非严格求值
一切都是表达式
call by value VS call by name - 惰性求值lazy evaluation
数据类型
语法
- val 常量
- var 变量
- lazy val 懒加载常量
字符串插值
使用s+${}12val s : String = "hello";s"${s} world";函数
123def functionName (param : ParamType)[: ReturnType] = {//function body}
|
|
if表达式
if(logical_exp) valA else valB1234val a = 1; a: Int = 1if (a == 1) a res4: AnyVal = 1if (a != 1) "not one" res5: Any = ()if (a != 1) "not one" else 1 res6: Any = 1for comprehension
123456789101112val l = List("a", "b", "c")for {s <- l //generatorif (s.length < 3) //filter} println(s)val result_for = for {s <- lsup = s.toUpperCase(); //variable bindingif (sup != "")} yield (sup) //generate new collectiontry, catch, finally
1234567try {Integer.parseInt("dog")} catch {case _ => 0; //_是通配符,=>赋值} finally {println("always be printed")}match
123456exp match{case p1 => val1case p2 => val2...case _ => valn}
|
|
求值策略
call by value 一般都是=使用,调用就计算call by name 调用不计算,只有等到执行才会计算
|
|
高阶函数
用函数作为形参或返回值的函数成为高阶函数
匿名函数
匿名函数anonymous function就是函数常量,也成为函数文字量function literal
在scala中匿名函数的定义格式为(形参列表) => {函数体}
柯里化 curried functoin
把具有多个参数的函数转化为一条函数链,每个节点上是单一参数
上面的例子可以看出来,柯里化可以复用函数
递归函数recuritive function
|
|
上面的m是计算的最新结果
例子
$$\sum_{i=a}^b f(x)=0$$
求a到b的区间和
|
|
打印结果