Scala Stack /:() method with example
In Scala, scala.collection.mutable implements Stack data structure. The /: method applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.
Method Definition – def /:[B](z: B)(op: (B, A) ? B): B
Returns – the result of inserting op between consecutive elements of this traversable or iterator.
Example #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
st
1
=
Stack(
1
,
2
,
3
)
// Applying /:() method
val
result
1
=
(
16
/
:
st
1
)(
_
+
_
)
val
result
2
=
(
16
/
:
st
1
)(
_
-
_
)
// Display output
print(result
1
)
print(
"\n"
)
print(result
2
)
}
}
Output:22 10Example #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
q
2
=
List(
11
,
12
,
13
,
14
,
15
)
// Applying /:() method
val
result
=
(
6
/
:
q
2
)(
_
+
_
)
// Display output
print(result)
}
}
Output:71