Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a Scala List as a Stack?

Tags:

scala

I am trying to solve a hw problem in Scala. A traditional solution require a stack but stacks have not been introduced in the class so far. Only lists have been introduced. My question is how can treat a list as a stack? In other words, how can I mimic pushing and popping elements on a list?

like image 359
awm Avatar asked Jan 02 '26 08:01

awm


1 Answers

I hope this will show the idea:

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val pushed0 = 0::x
push3: List[Int] = List(0, 1, 2, 3)

scala> val pop0 = pushed0.head
pop3: Int = 0
// it is actually more peek than fair pop 

scala> val stackAfterPop = pushed0.tail
stackAfterPop: List[Int] = List(1, 2, 3)

It will actually have much better syntax when you'll be acquainted with pattern matching (next week I guess):

scala> val popped::stack = pushed0
popped: Int = 0
stack: List[Int] = List(1, 2, 3)
like image 70
om-nom-nom Avatar answered Jan 04 '26 12:01

om-nom-nom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!