Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use scala.collection.immutable.Stack

Tags:

scala

I need something to store a LIFO. No need for traversing and other functions except for push and pop.

I've found special class in scala collection for creating a stack. But it lacks Nil object in pattern matching and other handy scala idioms. Immutable lists suit well at first glance, they have cons for construction and for extraction and that is all needed from LIFO.

Is there any reason behind scala.collection.immutable.Stack existence? Why I should prefer to use it, what are use cases to show its benefits?

like image 550
ayvango Avatar asked Jun 08 '12 00:06

ayvango


1 Answers

From the API documentation:

Note: This class exists only for historical reason and as an analogue of mutable stacks. Instead of an immutable stack you can just use a list.

And in a little more detail:

Immutable stacks are used rarely in Scala programs because their functionality is subsumed by lists: A push on an immutable stack is the same as a :: on a list and a pop on a stack is the same as a tail on a list.

So to answer your questions:

  1. Yes, there's a reason for its existence.
  2. No, you shouldn't prefer it over lists.
like image 98
Travis Brown Avatar answered Sep 30 '22 07:09

Travis Brown