码迷,mamicode.com
首页 > 其他好文 > 详细

scala编程第16章学习笔记(3)——List类的高阶方法

时间:2014-11-17 10:38:04      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   for   strong   div   

列表间映射:map、flatMap和foreach

1.xs map f 操作返回把函数f应用在xs的每个列表元素之后由此组成的新列表。如:

scala> List(1, 2, 3) map (_ + 1)
res0: List[Int] = List(2, 3, 4)

scala> val words = List("the", "quick", "brown", "fox")
words: List[String] = List(the, quick, brown, fox)

scala> words map (_.length)
res1: List[Int] = List(3, 5, 5, 3)

scala> words map (_.toList.reverse.mkString)
res2: List[String] = List(eht, kciuq, nworb, xof)

2.flatMap操作符与map类似,不过它的右操作元是能够返回元素列表的函数。它对列表的每个元素调用该方法,然后连接所有方法的结果并返回。map与flatMap的差异举例说明如下:

scala> words map (_.toList)
res3: 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)
res4: List[Char] = List(t, h, e, q, u, i, c, k, b, r, o, w, n, f, o, x)

List.range是可以创建某范围内所有整数列表的工具方法。例如:

scala> List.range(1, 5) flatMap (i => List.range(1, i) map (j => (i, j)))
res6: List[(Int, Int)] = List((2,1), (3,1), (3,2), (4,1), (4,2), (4,3))

3.foreach是第三种与映射类似的操作。它的右操作元是过程(返回Unit的函数)。它只是对每个列表元素都调用一遍过程。操作的结果仍然是Unit,不会产生结果列表。例如:

scala> var sum = 0
sum: Int = 0

scala> List(1, 2, 3, 4, 5) foreach (sum += _)

scala> sum
res9: Int = 15

列表过滤:filter、partition、find、takeWhile、dropWhile和span
1.xs filter p操作产生xs中符合p(x)为true的所有元素组成的列表。如:

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

scala> words filter (_.length == 3)
res11: List[String] = List(the, fox)

2.partition方法与filter类似,不过返回的是列表对。其中一个包含所有论断为真的元素,另一个包含所有论断为假的元素。
xs partition p  等价于 (xs filter p, xs filter (!p()))

举例如下:

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

3.find方法同样与filter方法类似,不过返回的是第一个满足给定论断的元素,而并不是全部。xs find p 操作以列表xs和论断p为操作元。返回可选值。如果xs中存在元素x使得p(x)为真,Some(x)将返回。否则,若p对所有元素都不成立,None将返回。举例如下:

scala> List(1, 2, 3, 4, 5) find (_ % 2 == 0)
res13: Option[Int] = Some(2)

scala> List(1, 2, 3, 4, 5) find (_  <= 0)
res15: Option[Int] = None

4. xs takeWhile p操作返回列表xs中最长的能够满足p的前缀。

 

scala编程第16章学习笔记(3)——List类的高阶方法

标签:style   blog   io   color   ar   sp   for   strong   div   

原文地址:http://www.cnblogs.com/gaopeng527/p/4102937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!