functional list, queues and package for concurrent
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package std.concurrent
|
||||
|
||||
abstract class FunctionalList<T>(val size: Int) {
|
||||
abstract val head: T
|
||||
abstract val tail: FunctionalList<T>
|
||||
|
||||
val empty : Boolean
|
||||
get() = size == 0
|
||||
|
||||
fun add(element: T) : FunctionalList<T> = FunctionalList.Standard(element, this)
|
||||
|
||||
fun reversed() : FunctionalList<T> {
|
||||
if(empty)
|
||||
return this
|
||||
|
||||
var cur = tail
|
||||
var new = of(head)
|
||||
|
||||
while(!cur.empty) {
|
||||
new = new.add(cur.head)
|
||||
cur = cur.tail
|
||||
}
|
||||
return new
|
||||
}
|
||||
|
||||
fun iterator() = object: Iterator<T> {
|
||||
var cur = this@FunctionalList
|
||||
|
||||
override fun next(): T {
|
||||
if(cur.empty)
|
||||
throw java.util.NoSuchElementException()
|
||||
|
||||
val head = cur.head
|
||||
cur = cur.tail
|
||||
return head
|
||||
}
|
||||
|
||||
override val hasNext: Boolean
|
||||
get() = !cur.empty
|
||||
}
|
||||
|
||||
class object {
|
||||
class Empty<T>() : FunctionalList<T>(0) {
|
||||
override val head: T
|
||||
get() = throw java.util.NoSuchElementException()
|
||||
override val tail: FunctionalList<T>
|
||||
get() = throw java.util.NoSuchElementException()
|
||||
}
|
||||
|
||||
class Standard<T>(override val head: T, override val tail: FunctionalList<T>) : FunctionalList<T>(tail.size+1)
|
||||
|
||||
fun <T> emptyList() = Empty<T>()
|
||||
|
||||
fun <T> of(element: T) : FunctionalList<T> = FunctionalList.Standard<T>(element,emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package std.concurrent
|
||||
|
||||
import java.util.concurrent.Executor
|
||||
import jet.Iterator
|
||||
|
||||
class FunctionalQueue<T>(
|
||||
val input: FunctionalList<T> = FunctionalList.emptyList<T>(),
|
||||
val output: FunctionalList<T> = FunctionalList.emptyList<T>()) {
|
||||
|
||||
val size : Int
|
||||
get() = input.size + output.size
|
||||
|
||||
val empty : Boolean
|
||||
get() = size == 0
|
||||
|
||||
fun add(element: T) = FunctionalQueue<T>(input add element, output)
|
||||
|
||||
fun addFirst(element: T) = FunctionalQueue<T>(input, output add element)
|
||||
|
||||
fun removeFirst() : #(T,FunctionalQueue<T>) =
|
||||
if(output.empty) {
|
||||
if(input.empty)
|
||||
throw java.util.NoSuchElementException()
|
||||
else
|
||||
FunctionalQueue<T>(FunctionalList.emptyList<T>(), input.reversed()).removeFirst()
|
||||
}
|
||||
else {
|
||||
#(output.head, FunctionalQueue<T>(input, output.tail))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user