Skip to content

Instantly share code, notes, and snippets.

@wataru420
Created September 11, 2012 04:50
Show Gist options
  • Save wataru420/3696033 to your computer and use it in GitHub Desktop.
Save wataru420/3696033 to your computer and use it in GitHub Desktop.
trait Queue[T]{
def head:T
def tail:Queue[T]
def append(x:T):Queue[T]
}
// クラス実装自体を格納するオブジェクト
object Queue{
// 待ち行列クラスの実装を行う非公開クラス
// 実装内容はこれまでのQueueと同じ
private class QueueImpl[T](
private val leading:List[T],
private val trailing:List[T]
// トレイトミックスインです
) extends Queue[T]{
def mirror = {
if(leading.isEmpty) new QueueImpl(trailing.reverse, Nil)
else this
}
def head:T = mirror.leading.head
def tail:QueueImpl[T] = {
val q = mirror
new QueueImpl(q.leading.tail, q.trailing)
}
def append(x:T) = new QueueImpl(leading, x::trailing)
}
// オブジェクト生成用のapplyメソッド
def apply[T](xs:T*):Queue[T] = new QueueImpl[T](xs.toList, Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment