美文网首页Scala代码改变世界
Scala基础(9)- 列表

Scala基础(9)- 列表

作者: 彤庆 | 来源:发表于2015-03-22 08:31 被阅读337次

    列表(List)应该是使用最多的数据结构了。

    列表的构造

    注意列表中的元素类型必须一致。

    val fruit = List("apples", "oranges", "pears")
    val nums: List[Int] = List(1, 2, 3, 4)
    

    构造列表的两个基本单位是Nil::。上面的构造可以写成

    val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) 
    val nums =1::(2::(3::(4::Nil)))
    

    理解这一点对列表的操作和模式匹配很有帮助。

    列表操作

    Scala列表有三个基本操作:

    • head 返回列表第一个元素
    • tail 返回一个列表,包含除了第一元素之外的其他元素
    • isEmpty 在列表为空时返回true

    对于Scala列表的任何操作都可以使用这三个基本操作来表达。比如插入排序算法就可以这样实现。

    def isort(xs: List[Int]): List[Int] =
        if (xs.isEmpty) Nil
        else insert(xs.head, isort(xs.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)
    

    列表的模式

    使用前面提到的模式匹配,可以使插入排序算法更加直观。

     def isort(xs: List[Int]): List[Int] = xs match {
              case List()   => List()
              case x :: xs1 => insert(x, isort(xs1))
    }
    def insert(x: Int, xs: List[Int]): List[Int] = xs match {
              case List()  => List(x)
              case y :: ys => if (x <= y) x :: xs
    }
    

    列表的常用操作

    下面的代码列举了Scala List的常用操作。

    scala> List(1, 2) ::: List(3, 4, 5) // 连接两个列表
    res0: List[Int] = List(1, 2, 3, 4, 5)
    
      scala> List(1, 2, 3).length //length
      res3: Int = 3
    // last and init
    val abcde = List('a', 'b', 'c', 'd', 'e')
    scala> abcde.last
    res4: Char = e
    scala> abcde.init
    res5: List[Char] = List(a, b, c, d)
    
    abcde.reverse
    res6: List[Char] = List(e, d, c, b, a)
    
    // take, drop and splitAt
    scala> abcde take 2
    res8: List[Char] = List(a, b)
    scala> abcde drop 2
    res9: List[Char] = List(c, d, e)
    scala> abcde splitAt 2
    res10: (List[Char], List[Char]) = (List(a, b),List(c, d, e))
    
    // flatten 
    scala> List(List(1, 2), List(3), List(), List(4, 5)).flatten
    res14: List[Int] = List(1, 2, 3, 4, 5)
    
    // zip and unzip 
    scala> abcde.indices zip abcde
    res17: scala.collection.immutable.IndexedSeq[(Int, Char)] =
                IndexedSeq((0,a), (1,b), (2,c), (3,d), (4,e))
    scala> abcde.zipWithIndex
    res18: List[(Char, Int)] = List((a,0), (b,1), (c,2), (d,3),
                (e,4))
    scala> zipped.unzip
    res19: (List[Char], List[Int]) = (List(a, b, c),List(1, 2, 3))
    
    
    //  toString and mkString
    
    scala> abcde.toString
            res20: String = List(a, b, c, d, e)
    scala> abcde mkString ("[", ",", "]")
            res21: String = [a,b,c,d,e]
    

    列表的常用高阶方法

    高阶方法是指包含函数作为参数的方法。这些方法是Scala作为一个函数式语言所特有的,能够方便的实现列表的转变(Trasnformation)。最近Java8也引入了类似的方法集合。

    map, flatmap

    xs map f 就是将函数f作用于List xs中的每个元素,返回一个新的List。比如:

            scala> List(1, 2, 3) map (_ + 1)
            res32: List[Int] = List(2, 3, 4)
            scala> val words = List("the", "quick", "brown", "fox")
            words: List[java.lang.String] = List(the, quick, brown, fox)
            scala> words map (_.length)
            res33: List[Int] = List(3, 5, 5, 3)
            scala> words map (_.toList.reverse.mkString)
            res34: List[String] = List(eht, kciuq, nworb, xof)
    

    flatmap和map十分相似,唯一的区别就是返回时会把所用列表中的元素连起来,生成一个扁平的列表。下面的例子比较了map和flatmap。

            scala> words map (_.toList)
            res35: List[List[Char]] = List(List(t, h, e), List(q, u, i,
                c, k), List(b, r, o, w, n), List(f, o, x))
            scala> words flatMap (_.toList)
            res36: List[Char] = List(t, h, e, q, u, i, c, k, b, r, o, w,
                n, f, o, x)
    

    filter

    xs filter p,返回一个列表,包含xs中满足predicate p的元素。比如:

    scala> List(1, 2, 3, 4, 5) filter (_ % 2 == 0) res40: List[Int] = List(2, 4)
    

    fold

    另外一类常用的列表操作是将某种操作以某种累计的形式作用于列表中的元素。这就是fold。通常又分为foldLeftfoldRight,只是执行顺序不同。比如:

    scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n)
    res0: Int = 55
    

    这里0为初始值(记住numbers是List[Int]类型),m作为一个累加器。从1加到10。如果使用foldRight那就是从10加到1。

    此外,还有很多高阶方法比如range, fillsortWith等等,不再赘述。

    相关文章

      网友评论

        本文标题:Scala基础(9)- 列表

        本文链接:https://www.haomeiwen.com/subject/xdtgxttx.html