Scala学习笔记21【Scala List之模式匹配实战】

package com.yl.Scala

object ListTest {
  def main(args: Array[String]){

    //声明方式1
    val bigData = List("Hadoop", "Spark")
    val data = List(1,2,3)
    //声明方式2
    val bigData2 = "Hadoop" :: ("Spark" :: Nil) //结果和List("Hadoop", "Spark")一样
    val data2 = 1 :: 2 :: 3 :: Nil           //结果和List(1,2,3)一样

    println(data.isEmpty)  //判断是否为空 false
    println(data.head)     //获取首元素 1
    println(data.last)     //获取尾部元素 3
    println(data.tail.head)//获取首部外的第一个元素(也就是第二个元素) 2

    //列表赋值
    val List(a, b) = bigData
    println("a = " + a + "," + "b = " + b)  //a = Hadoop,b = Spark

    val x :: y :: z :: Nil= data  //加Nil以表明取的是三个元素x,y,z
    println("x = " + x + "," + "y = " + y + "," + "z = " + z) //x = 1,y = 2,z = 3

    val aListElement :: otherElement = data  //实际只取前一个元素,后面的元素放入新列表otherElement中了
    println("aListElement = " + aListElement + 
            ", otherElement = " + otherElement) //aListElement = 1, otherElement = List(2, 3)


    //List模式匹配案例:对List的元素排序
    val exampleList = List(1,4,5,6,26,25,6,2,36)

    def sortList(list: List[Int]): List[Int] = list match{
      //为空则直接返回空List 
      case List()       => List()                        
      //若不为空,将首元素,和剩余元素构成的列表分离,交予compute函数处理
      case head :: tail => compute(head, sortList(tail))  
    }

    //将要排序的列表的 首元素 及 剩余元素列表 作参数进行处理
    def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match{
      //剩余元素列表为空,则将data添加进List()返回
      case List()       => List(data) 
      //若不为空,data小于dataSet的首元素->则将data添加至dataSet的首部,否则继续执行campute(),与dataSet的第二个元素比较,如此循环
      case head :: tail => if (data < head) data :: dataSet else head :: compute(data, tail)
    }

    val sortedList = sortList(exampleList)
    println("排序后的List: " + sortedList)
  }
}

/* 执行结果 false 1 3 2 a = Hadoop,b = Spark x = 1,y = 2,z = 3 aListElement = 1, otherElement = List(2, 3) 排序后的List: List(1, 2, 4, 5, 6, 6, 25, 26, 36) */

你可能感兴趣的:(scala,List模式匹配)