- List is immutable, 底层实现用的数据结构上linked list. head 是第一个元素,tail是其余元素
last是最后一个元素, init是除最后一个元素之外的元素
2. 插入排序算法
package chapter16 object TestList extends App{ def isort(x: List[Int]): List[Int] = if (x.isEmpty) x else insert(x.head, isort(x.tail)) def insert(x: Int, xs: List[Int]): List[Int] = { if (xs.isEmpty || x <= xs.head) x :: xs else xs.head :: insert(x, xs.tail) } val list0 = List(4,5,3,6,1,7,0) println(isort(list0)) }
3. 使用pattern matching改进代码
package chapter16 object TestList extends App{ def isort(xs: List[Int]): List[Int] = xs match { case List() => xs case x::xs1 => insert(x, isort(xs1)) } def insert(x: Int, xs: List[Int]): List[Int] = xs match { case List() => x::xs case y::ys => if (x <= y) x :: xs else y::insert(x, ys) } val list0 = List(4,5,3,6,1,7,0) println(isort(list0)) }
4. 一阶方法
This section explains most first-order methods defined in the List class. A method is first-order if it does not take any functions as arguments.
不以函数为参数的方法称为一阶方法
5. 拼接实现reverse方法
def reverse(xs: List[Int]): List[Int] = xs match { case List() => xs case y::ys => reverse(ys):::List(y) } val list0 = List(4,5,3,6,1,7,0) println(reverse(list0)) //List(0, 7, 1, 6, 3, 5, 4)
6.扁平化List
The flatten method takes a list of lists and flattens it out to a single list
7.drop 去掉前 n个, take 取前 n个
8.map 相当于R语言中的lapply
9.flatmap 如果 f返回的是list,则把所有的返回值拼接在一起返回
时间: 2024-10-25 18:43:24