这一篇是来自官网的Scala By Example
即Tutorial后更详细地对Scala怎么用给了示例
该文一开始给了一个快速排序的示例
版本一:
def sort(xs: Array[Int]) { def swap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j);xs(j) = t } def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length - 1) }
这里,除了定义方法和变量的def val 还有行尾的";",好像其他和Java也多大区别
再来看一个更能体现Scala特点的编程方法,同样是快速排序
def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) } }
这样的编程方式更能体现快速排序的本质:
- 如果数组xs只有一个元素,那么久直接返回xs(这里连return关键字都没有)
- 如果xs有一个以上元素,则取中间值
- 根据大于、等于、小于分块
- 先对前面两个Array排序,再排第三个,然后拼接到前面两个的结果。(这应该是concat()函数的功能)
前者是命令式编程,改变了初始Array;而后者是函数是编程,产生了一个新的Array,只不过这需要占用更多的内存
这里的filter是判定函数
def filter(p: T => Boolean): Array[T]
返回判定为true的结果。像filter这样以别的函数为参数或作为结果返回称为高阶函数
Scala不区分标识符和运算符名称,任何标示符都可以作为中缀运算符,所以 xs filter (pivot >) 和xs.filter(pivot >) 是等价的
这里我们还可以看到代码中(pivot >)这部分是没有参数的,这就是部分应用函数,也可以写成 x => pivot > x 。这是一个匿名函数,Scala编译器会自动根据上下文推理。
def While (p: => Boolean) (s: => Unit) { if (p) { s ; While(p)(s) } }
TODO
1.Programing with Actors and Message
这里用一个电子竞拍服务讲解Actor模型。
2.Expressions and Simple Functions
3.First-class Functions
4.Class and Objects
5.Case Classes and Pattern Matching
6.Generic Types and Methods
7.Lists
8.For-Comprehensions
9.Mutable State
10.Computing with Streams
11.Lazy Values
12.Implicit Parameters and Conversions
13.Hindley/Milner Type Inference
14.Abstractions for Concurrency