관리 메뉴

HAMA 블로그

스칼라 강좌 (9) - Stack / Queue 본문

Scala

스칼라 강좌 (9) - Stack / Queue

[하마] 이승현 (wowlsh93@gmail.com) 2016. 6. 26. 14:15


Queue 

mutable
val queue = new scala.collection.mutable.Queue[String]
queue += "a"
queue ++= List("b", "c")
println(queue.dequeue) => a

immutable
import scala.collection.immutable.Queue val queue1: Queue[String] = Queue("Plain Donut", "Strawberry Donut", "Chocolate Donut")
val queue2: Queue[String] = queue1 :+ "Glazed Donut"
val enqueue: Queue[String] = queue1.enqueue("Vanilla Donut")
val dequeue: (String, Queue[String]) = queue1.dequeue
val queue3: Queue[String] = queue1 ++ Queue[String]("Glazed Donut", "Vanilla Donut")val emptyQueue: Queue[String] = Queue.empty[String]

Stack 
mutable
val stack = new scala.collection.mutable.Stack[Int]
stack.push(1)
stack.push(2)
println(stack.pop) => 2

immutable

scala> stack.push(4) res26: scala.collection.immutable.Stack[Int] = Stack(4, 1, 2, 3) scala> stack.pop() Stack(1,2,3) scala> stack.top() Stack(1)

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.

val stack2: List[String] = List("Plain Donut","Strawberry Donut","Chocolate Donut") val stack3: List[String] = "Vanilla Donut" :: stack2
val stack4: List[String] = "Glazed Donut" :: "Vanilla Donut" :: stack2
val stack5: List[String] = stack2.tail //tail은 pop과 같고, head 하면 top과 같을듯
result : List(Strawberry Donut, Chocolate Donut)

val emptyStack: List[String] = List.empty[String]


0 Comments
댓글쓰기 폼