Created
September 13, 2010 16:29
-
-
Save kmizu/577559 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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