Scala forall 示例? [英] Scala forall example?

查看:57
本文介绍了Scala forall 示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了 Google 搜索,但找不到合适的 forall 示例.它有什么作用?为什么它需要一个布尔函数?

I tried Google search and could not find a decent forall example. What does it do? Why does it take a boolean function?

请给我一个参考(Scaladoc 除外).

Please point me to a reference (except the Scaladoc).

推荐答案

forall 方法接受一个返回布尔值的函数 p.forall 的语义表示:如果对于集合中的每个 xp(x) 为真,则返回 true.

The forall method takes a function p that returns a Boolean. The semantics of forall says: return true if for every x in the collection, p(x) is true.

所以:

List(1,2,3).forall(x => x < 3)

表示:true 如果 1、2 和 3 小于 3,则 false 否则.在这种情况下,它将评估为 false,因为并非所有元素都小于 3:3 不小于 3.

means: true if 1, 2, and 3 are less than 3, false otherwise. In this case, it will evaluate to false since it is not the case all elements are less than 3: 3 is not less than 3.

有一个类似的方法 exists 返回 true 如果至少一个元素 x 在集合使得 p(x) 为真.

There is a similar method exists that returns true if there is at least one element x in the collection such that p(x) is true.

所以:

List(1,2,3).exists(x => x < 3)

表示:true,如果1、2和3中的至少一个小于3,否则false.在这种情况下,它将评估为 true 因为它是某些元素小于 3 的情况:例如1 小于 3.

means: true if at least one of 1, 2, and 3 is less than 3, false otherwise. In this case, it will evaluate to true since it is the case some element is less than 3: e.g. 1 is less than 3.

这篇关于Scala forall 示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆