Skip to content

Instantly share code, notes, and snippets.

val <T> List<T>.size: Int
get() = when (this.isEmpty()) {
true -> 0
false -> 1 + this.tail.size
}
fun sum(xs: List<Int>): Int = when (xs.size) {
0 -> 0
else -> xs.head + sum(xs.tail)
}
fun sum(xs: List<Int>): Int = when (xs.size) {
0 -> 0
else -> {
val head = xs.head
val tailSum = sum(xs.tail)
head + tailSum
}
}
tailrec fun sum(xs: List<Int>, acum: Int): Int = when (xs.size) {
0 -> acum
else -> sum(xs.tail, xs.head + acum)
}
fun sum(xs: List<Int>):Int {
tailrec fun sumInner(xs: List<Int>, acum: Int): Int = when (xs.size) {
0 -> acum
else -> sumInner(xs.tail, xs.head + acum)
}
return sumInner(xs, 0)
}
fun <T, R> List<T>.map(f: (T) -> R): List<R> = when (this.size) {
0 -> listOf()
else -> f(head) + tail.map(f)
}
operator fun <T> List<T>.plus(xs: List<T>): List<T> = when (xs.size) {
0 -> ArrayList(this)
else -> (this + xs.head) + xs.tail
}
operator fun <T> T.plus(xs: List<T>): List<T> = listOf(this) + xs
fun <T> List<T>.filter(f: (T) -> Boolean): List<T> = when (this.size) {
0 -> listOf()
else -> if (f(head)) head + tail.filter(f) else tail.filter(f)
}
fun <T, R> reduce(s: T, xs: List<R>, f: (T, R) -> T): T = when (xs.size) {
0 -> s
else -> reduce(f(s, xs.head), xs.tail, f)
}
fun <T> reduceSame(xs: List<T>) = reduce(listOf<T>(), xs)
{ ys, s -> ys + s }