Created
September 17, 2016 20:20
-
-
Save dcapwell/445c62d02e1089b6d87158a9801002d6 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
//fun <A> nil(): ConsList<A> { | |
// return ConsList.Nil<A> | |
//} | |
sealed class ConsList<A> : Iterable<A> { | |
fun cons(value: A): ConsList<A> { | |
return Cons(value, this); | |
} | |
fun isEmpty() : Boolean = this !is Nil | |
fun size(): Int { | |
tailrec fun recSize(xs: ConsList<A>, acc: Int): Int = | |
if (xs is Cons<A>) recSize(xs.parent, acc + 1) | |
else acc | |
return recSize(this, 0) | |
} | |
override fun iterator(): Iterator<A> { | |
return ConsIterator(this) | |
} | |
override fun toString(): String { | |
val sb = StringBuilder("[") | |
var self : ConsList<A> = this | |
while (self is Cons<A>) { | |
sb.append(self.value).append(",") | |
self = self.parent | |
} | |
sb.setLength(sb.length - 1) | |
sb.append("]") | |
return sb.toString() | |
} | |
class Cons<A>(val value: A, val parent: ConsList<A>) : ConsList<A>() | |
class Nil<A> : ConsList<A>() | |
private class ConsIterator<A>(var self: ConsList<A>) : AbstractIterator<A>() { | |
override fun computeNext() { | |
val current = self | |
if (current !is Cons<A>) | |
return done() | |
setNext(current.value) | |
self = current.parent | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment