Friday, June 14, 2013

Simple custom Stack[Type] implementation in Scala.

trait MyStack[T] {
 def push(x:T):MyStack[T]
 def pop:MyStack[T]
 def isEmpty:Boolean
 def top:T
 def length:Int
}

object MyStack {

 def apply[M](xs:M*):MyStack[M] = new MyStackImpl[M](xs.toList)

 class MyStackImpl[M](var xs:List[M]) extends MyStack[M] {

  def push(pu:M):MyStackImpl[M] = new MyStackImpl[M](pu::xs)

  def pop:MyStackImpl[M] = new MyStackImpl(xs.tail)

  def top:M = xs.head

  def isEmpty:Boolean = if(xs.length==0) true else false
                def head:M = xs.head

  def length:Int = xs.length
 }
}

def myTest {
val stack1 = MyStack(1,2,3,4,5) // This is similar to Mystack apply (1,2,3,4,5)
println(stack1.top) // Prints the top most element of the stack
val stack2 = stack1.push(5)
println(stack2.top) // After 5 is added to the top, this statement prints 5 as the top element
println(stack2.pop.top) // This statement pops the top element (5) and prints the top element (1)
println(stack2.pop.pop.pop.pop.pop.pop.length) // This will print 0 since all the elements of                          the stack are popped.
}
myTest


//OUTPUT
1
5
1
0


Explanation:
1) Create a Typed trait (MyStack[T])which can be used to create Stacks that can accommodate any types.
2) The companion object is MyStack (with the same name as that of the trait). This becomes a  companion object of all the concrete classes which are mixed with the trait MyStack. This will ensure the object has access to the private members (if any, in this case we don't have private members) of the concrete classes.
3) The apply method of the object has to be implemented. The input parameter is a sequence of
elements of type M. The sequence will be converted into a List (using seq.toList method) for processing.
The apply method allows us to use the class as a Factory. for eg: MyStack(1,2,3,4,5) which has the implementation MyStack.apply(1,2,3,4,5) under the hood.
4) This class MyStackImpl  is the concrete implementation of the custom Stack trait. The constructor is a list
which was created using the Sequence element from the input parameter of the apply method present
in this object.
5) The push method of the MyStackImpl object adds an element of type M at the top of the stack and returns a new MyStackImpl object with the newly added element at the top
6) The pop method of the MyStackImpl  removes(pops) the top most element from the stack and returns another MyStackImpl object without the popped element.
7) The top method returns the top most element from the stack.
8) The isEmpty methods returns true if there are no elements in the stack and false when at least one element is present.
9) This length function returns the length of the stack.




No comments:

Post a Comment