Created
December 18, 2011 16:34
-
-
Save dekosuke/1493847 to your computer and use it in GitHub Desktop.
SnocList written in Scala
This file contains 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
object SnocList{ | |
def empty = SnocNil | |
} | |
sealed trait SnocList[+A] { | |
def isEmpty : Boolean | |
def head : A | |
def tail : SnocList[A] | |
def ::>[B >: A] (x: B): SnocList[B] = new ::>[B](this, x) | |
def map[B](f: A=>B) : SnocList[B] = this match { | |
case SnocNil => SnocNil | |
case xs ::> x => xs.map(f) ::> f(x) | |
} | |
def foldLeft[B](z: B)(f: (B, A) => B): B = this match { | |
case SnocNil => z | |
case xs ::> x => f(xs.foldLeft(z)(f), x) | |
} | |
def foldRight[B](z: B)(f: (A, B) => B): B = { | |
var acc = z | |
var these = this | |
while (!these.isEmpty) { | |
acc = f(these.head, acc) | |
these = these.tail | |
} | |
acc | |
} | |
override def toString() = { | |
val contents = getContents() | |
"SnocList(" + contents + ")" | |
} | |
def getContents():String = this match { | |
case SnocNil => "" | |
case SnocNil ::> x => x.toString() | |
case xs ::> x => xs.getContents() + ", " + x.toString() | |
} | |
} | |
case object SnocNil extends SnocList[Nothing] { | |
override def isEmpty = true | |
def head: Nothing = throw new NoSuchElementException("head of empty list") | |
def tail: SnocList[Nothing] = throw new NoSuchElementException("tail of empty list") | |
} | |
case class ::>[B](tl:SnocList[B], hd: B) extends SnocList[B] { | |
override def isEmpty = false | |
def head : B = hd | |
def tail : SnocList[B] = tl | |
} | |
//sample | |
val l = SnocNil ::> 1 ::> 2 ::> 3 | |
println(""+l) | |
println(""+l.map(x=>2*x)) | |
println(""+l.map(x=>2*x).foldLeft(1)( _ + _ )) | |
println(""+l.foldLeft(SnocList.empty:SnocList[Int])((x,y)=>(x ::> y))) | |
println(""+l.foldRight(SnocList.empty:SnocList[Int])((x,y)=>(y ::> x))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment