Scala Stack forall()方法及示例
在Scala Stack类中, forall() 方法被用来检查一个谓词是否对堆栈的所有元素都成立。
方法定义: def forall(p: (A) => Boolean):Boolean
返回类型。如果谓词对堆栈中的所有元素都成立,则返回真,否则返回假。
例子 #1:
// Scala program of forall()
// method
// Import Stack
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating stack
val s1 = Stack(6, 2, 3, 4, 5)
// Print the stack
println(s1)
// Applying forall method
val result = s1.forall(x => {x % 7 == 0})
// Display output
println("All the elements are divisible by 7: " + result)
}
}
输出。
Stack(6, 2, 3, 4, 5)
All the elements are divisible by 7: false
例子#2。
// Scala program of forall()
// method
// Import Stack
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating stack
val s1 = Stack(7, 9, 3, 1, 5)
// Print the stack
println(s1)
// Applying forall method
val result = s1.forall(x => {x % 2 == 1})
// Display output
println("All the elements are odd: " + result)
}
}
输出。
Stack(7, 9, 3, 1, 5)
All the elements are odd: true
极客教程