ArrayStack Overview#
It's simple scala program that implements Scala Iterable interface and test it.* See it in my wiki
Source#
ArrayStack  case class ArrayStack[T](size: Int) extends Iterable[T] {
  // stack
  val stack : Array[T] = new Array[T](size);
  // number of items in stack
  var idx : Int = 0;
  //---------------------------------------- Stack Methods
  def push(item: T) = { stack(idx) = item ; idx += 1; }
  def pop() : T = { idx -= 1; stack(idx); }
  //---------------------------------------- Iterable Interface
  //* check if stack is empty
  override def isEmpty : Boolean = {idx <= 0; }
  //* return Iterator
  def elements : Iterator[T] = new Iterator[T]  {
    var i = idx - 1;
    override def hasNext:Boolean = { i >= 0; }
    override def next : T = { i -= 1; return stack(i+1); }
  }
  //* Apply a function f to all elements of this iterable object.
  override def foreach(f : T => Unit){
    var currentIndex = idx - 1;
    while(currentIndex >= 0){
      f(stack(currentIndex).asInstanceOf[T]);
      currentIndex -= 1;
    }
  }
}
ArrayStackTester
object ArrayStackOfString extends Application {
//--------------------------------------------- Main Method
// create array stack
val astack = new ArrayStack[String](100);
Console.printf("> ArrayStack of Size %d created.\n\n", astack.size);
// test stack
def doStack {
  Console.readLine() match {
    case null =>
    case "" => Console.println("> Bye !!");
    case "-" if astack.isEmpty => Console.println("@@ Stack is Empty "); doStack;
    case "-" => Console.printf("> Poped : %s\n", astack.pop()); doStack;
    
    case item:String => {
      astack.push(item);
      Console.printf("> Pushed : %s \n", item);
      doStack;
    }                
  }
}
doStack;
// printout stack
Console.printf("> Stack dump\n");
for(item <- astack) {
  Console.println(item);
}
}
Result#
> ArrayStack of Size 100 created.
Array
> Pushed : Array
Stack
> Pushed : Stack
Of
> Pushed : Of
String
> Pushed : String
-
> Poped : String
-
> Poped : Of
> Bye !!
> Stack dump
Stack
Array
 

댓글 없음:
댓글 쓰기