本文主要介绍 Scala 中的 List
- List 是不可变的
- 实现的方式是递归的方式,比如,
List(1, 2, 3)
可以看成是1
和List(2,3)
组成的,List(2, 3)
可以看成是2
和List(3)
组成的,以此类推 - 所以,所有 List 是以一个 empty list
NIL
和 构建操作::
为基础构建的 - 所以,
List(1, 2, 3)
可以看成是1::(2::(3::Nil))
,根据操作符优先级,::
是右结合的,所以等价于1::2::3::Nil
,等价于Nil.::(3).::(2).::(1)
val a = List(1, 2, 3, 4)
a.head
// 1
a.tail
// List(2, 3, 4)
// 用于模式匹配
object test {
def main(args: Array[String]): Unit = {
val a = List(1,2,3,4,5)
a match{
case x::Nil => println("type 1, ", x)
case Nil => println("type 2, ", Nil)
case 1::2::x => println("type 3, ", x)
case _ => println("do not match")
}
}
}
// 模式匹配 插入排序
object test {
def main(args: Array[String]): Unit = {
println(lsort(List(3,1,5,4,6,8)))
}
def lsort(xs: List[Int]): List[Int] = {
xs match {
case Nil => Nil
case p :: ps => insert(p, lsort(ps))
}
}
def insert(p: Int, ps: List[Int]): List[Int] = {
ps match {
case Nil => List(p)
case y::ys => if (p<=y) p::ps else y::insert(p, ys)
}
}
}
- 常用方法:
val a = List(1,2,3,4,5)
// head 和 tail 是配套操作
a.head
// 1
a.tail
// List(2,3,4,5)
// init 和 last 是配套操作
a.init
// List(1,2,3,4)
a.last
// 5
// take 和 drop 是配套操作
a.take(2)
// List(1, 2)
a.drop(2)
// List(3, 4, 5)
// concat
val b = List(1,2,3)
a ++ b
// or
a ::: b
// List(1,2,3,4,5,1,2,3)
// 获取index
// List中有的话 就返回index 没有的话就返回-1
a.indexOf(1)
// 0
// 分割成两个List
a.splitAt(2)
// (List(1, 2), List(3, 4, 5))
- 根据 List 的结构如何自己设计方法
// last
def last[A](xs: List[A]): A = {
xs match{
case List() => throw new Error("empty list")
case List(x) => x
case y::ys => last(ys)
}
}
// init
def init[A](xs: List[A]): List[A] = {
xs match{
case List() => throw new Error("empty list")
case List(x) => Nil
case y::ys => y :: init(ys)
}
}
// concat
def concat[A](xs: List[A], ys: List[A]): List[A] = {
xs match {
case Nil => ys
case x::xxs => x :: concat(xxs, ys)
}
}
// reverse
def reverse[A](xs: List[A]): List[A] = {
xs match {
case Nil => xs
case y :: ys => reverse(ys) ++ List(y)
}
}
参考资料:《Functional Programming Principles in Scala》