Scala Stack :() 方法与示例
在 Scala 中,scala.collection.mutable 实现了 Stack 数据结构。 :\ 方法将二元运算符应用于起始值和此可遍历或迭代器的所有元素,从右到左。
Method Definition – def :\[B](z: B)(op: (A, B) ? B): B
Returns – the result of inserting op between consecutive elements of this traversable or iterator.
示例 #1:
// Scala program of mutable stack :\()
// method
// Import Stack
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
val st1 = Stack(1, 2, 3)
// Applying :\() method
val result1 = (st1 :\ 16 )(_+_)
val result2 = (st1 :\ 16)(_-_)
// Display output
print(result1)
print("\n")
print(result2)
}
}
输出:
22
-14
示例 #2:
// Scala program of mutable stack :\() method
// Import Stack
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a stack
val q2 = List(11, 12, 13, 14, 15)
// Applying :\() method
val result = (q2 :\ 6)(_+_)
// Display output
print(result)
}
}
输出:
71