前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Scala Collections集合的几个重要概念

Scala Collections集合的几个重要概念

作者头像
Albert陈凯
发布2018-04-04 15:19:29
4960
发布2018-04-04 15:19:29
举报
文章被收录于专栏:Albert陈凯

几个重要的概念

谓词是什么(What a predicate is)

A predicate is simply a method, function, or anonymous function that takes one or more parameters and returns a Boolean value. For instance, the following method returns true or false, so it’s a predicate:

代码语言:javascript
复制
def isEven (i: Int) = if (i % 2 == 0) true else false

谓词就是一个方法,一个函数、一个匿名函数 接受一个或者多个参数,返回一个Boolean值,如上面这个函数啊的返回值就是true或者false,所以它是一个谓词

匿名函数是什么( What an anonymous function is):

The concept of an anonymous function is also important. here’s an example of the long form for an anonymous function:

代码语言:javascript
复制
(i: Int) => i % 2 == 0

Here’s the short form of the same function:

代码语言:javascript
复制
_ % 2 == 0

匿名函数是一个很重要的概念,上面第一段代码一个完整的匿名函数的例子,下面一个简化版的例子,他们看起来并不像,但当在集合里用到filter方法时,这种简短的代码会非常强大

代码语言:javascript
复制
scala> val list = List.range(1, 10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> val events = list.filter(_ % 2 == 0) 
events: List[Int] = List(2, 4, 6, 8)

隐式循环( Implied loops)

This is a nice lead-in into the third topic: implied loops. As you can see from that example, the filter method contains a loop that applies your function to every element in the collection and returns a new collection. You could live without the filter method and write equivalent code like this: 这里引入了隐式循环。如上例中所见filter方法包含了一个循环,会遍历集合里面的每个元素,然后返回一个新的集合,也可不用filter方法用下列代码实现这个功能

代码语言:javascript
复制
for {
    e <- list
    if e % 2 == 0 
   } yield e

But I think you’ll agree that the filter approach is both more concise and easier to read. 但是我想你也会同意filter这种方式既精简又易读 Collection methods like filter, foreach, map, reduceLeft, and many more have loops built into their algorithms. As a result, you’ll write far fewer loops when writing Scala code than with another language like Java. 像filter、foreach、map、reduceLeft和许多类似的集合方法都自带隐式循环。所以相比JAVA,Scala可以少写很多循环

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.06.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 几个重要的概念
    • 谓词是什么(What a predicate is)
      • 匿名函数是什么( What an anonymous function is):
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档