Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created September 13, 2010 16:29
Show Gist options
  • Save kmizu/577559 to your computer and use it in GitHub Desktop.
Save kmizu/577559 to your computer and use it in GitHub Desktop.
package object stack {
trait StackSignature {
type Stack[T]
def empty[T]: Stack[T]
def push[T](s: Stack[T], e: T): Stack[T]
def peek[T](s: Stack[T]): T
def pop[T](s: Stack[T]): Stack[T]
def isEmpty[T](s: Stack[T]): Boolean
}
val StackModule: StackSignature = new StackSignature {
case class Stack[T](content: List[T])
def empty[T] = Stack[T](Nil)
def push[T](s: Stack[T], e: T) = s.copy(content = e::s.content)
def peek[T](s: Stack[T]) = s.content.head
def pop[T](s: Stack[T]) = s.copy(content = s.content.tail)
def isEmpty[T](s: Stack[T]) = s.content == Nil
}
}
// Usage
// import stack._
// val s1 = StackModule.empty[String]
// val s2 = StackModule.push(s1, "FOO")
// println(StackModule.peek(s2)) // FOO
// println(s2.isEmpty) // false
// val s3 = StackModule.pop(s2)
// println(s3.isEmpty) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment