Scala 系列 - List

本文主要介绍 Scala 中的 List

  • List 是不可变的
  • 实现的方式是递归的方式,比如,List(1, 2, 3)可以看成是1List(2,3)组成的,List(2, 3)可以看成是2List(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》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值