Skip to content

Instantly share code, notes, and snippets.

@syafdia
Last active October 16, 2018 06:40
Show Gist options
  • Save syafdia/8357f08c62969e15690b5fcec5503585 to your computer and use it in GitHub Desktop.
Save syafdia/8357f08c62969e15690b5fcec5503585 to your computer and use it in GitHub Desktop.
package com.syafdia.github.dummykotlin.datastructure
sealed class LinkedList<out T> {
fun filter(f: (v: T) -> Boolean): LinkedList<T> {
return when (this) {
is Nil -> Nil
is Node<T> -> when (f(head)) {
true -> Node(head, tail.filter(f))
false -> tail.filter(f)
}
}
}
fun <U> map(f: (v: T) -> U): LinkedList<U> {
return when (this) {
is Nil -> Nil
is Node<T> -> Node(f(head), tail.map(f))
}
}
fun <U> reduce(initial: U, f: (acc: U, v: T) -> U): U {
return when (this) {
is Nil -> initial
is Node<T> -> tail.reduce(f(initial, head), f)
}
}
fun size(): Int {
return reduce(0) { total, _ ->
total + 1
}
}
override fun toString(): String {
return when (this) {
is Nil -> "Nil"
is Node<T> -> "($head, $tail)"
}
}
object Nil : LinkedList<Nothing>()
data class Node<T>(
val head: T,
val tail: LinkedList<T> = Nil
): LinkedList<T>()
companion object {
fun <T> of(
head: T,
tail: LinkedList<T> = Nil
): LinkedList<T> {
return Node(head, tail)
}
}
}
fun runDataStructure() {
val lList = LinkedList.of(
head = "B",
tail = LinkedList.of(
head = "C",
tail = LinkedList.of(
head = "D"
)
)
)
assertEquals(3, lList.size())
assertEquals(
"> AxCxDx",
LinkedList.Node("A", lList)
.map { it + "x" }
.filter { !it.contains("Bx") }
.reduce("> ") { acc, v: String -> acc + v }
)
}
fun <T> assertEquals(a: T, b: T) {
if (a != b) {
throw Exception("$a and $b is not equals")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment