import java.awt.Color object HelloWorld { def main(args: Array[String]) { var queueOfPoints = MyQueue(new Point()) var queueOfPixels = MyQueue(new Pixel(2,3, Color.red)) val queueOfPoints01 = queueOfPoints.enqueue(new Pixel(1, 2)) println (queueOfPoints.first.toString()) println (queueOfPixels.first.toString()) println (queueOfPoints01.first.toString()) println( queueOfPoints01.dequeue.first.toString() ) queueOfPoints = queueOfPixels println(queueOfPoints.first.toString()) } class Point( var x:Double = 0.0, var y:Double = 0.0 ) { override def toString = "[" + x + ", " + y + "]" } class Pixel( xp:Double=0.0, yp:Double=0.0, var color:Color = Color.BLACK ) extends Point(xp, yp) { override def toString = super.toString + " " + color } class UnderflowException(msg: String) extends Exception(msg) class MyQueue[+T] private(private val queue: (List[T], List[T])) { def enqueue[S >: T](element: S): MyQueue[S] = { val (beginningOfQueue, endOfQueue) = queue normalize(beginningOfQueue, element :: endOfQueue) } private def normalize[S >: T](list1: List[S], list2: List[S]) = (list1, list2) match { case (Nil, endOfQueue) => new MyQueue[S]((endOfQueue.reverse, Nil)) case normalQueue => new MyQueue(normalQueue) } def dequeue: MyQueue[T] = queue match { case (_ :: tail, endOfQueue) => normalize(tail, endOfQueue) case _ => MyQueue.empty } def first: T = queue._1 match { case (head :: _) => head case _ => throw new UnderflowException("first") } def isEmpty: Boolean = queue._1 == Nil override def equals(obj: Any): Boolean = obj match { case obj: MyQueue[_] => queue._1 ++ queue._2.reverse == obj.queue._1 ++ obj.queue._2.reverse case _ => false } } object MyQueue { def apply[T](xs: T*) = new MyQueue[T](xs.toList, Nil) def empty[T] = new MyQueue[T](Nil, Nil) } }