I am learning Kotlin and functional programming. I have to implement own functions for a stealed class list to get a deep understanding of higher functions.
This is the code of the stealed class
sealed class List <T> {
class Node <T> (val head : T, val tail : List<T>) : List<T> () {
override fun toString () =
"${head.toString()} , ${tail.toString()}"
}
object Nil : List<Nothing> () {
override fun toString () = "NIL"
}
companion object {
operator
fun <T> invoke (vararg values : T ) : List<T>{
val empty = Nil as List<T>
val res = values.foldRight( empty , { v, l -> l.addFirst(v) })
return res
}
}
fun addFirst ( head : T ) : List<T> = Node (head , this)
fun removeFirst () : List <T> = when (this) {
is Nil -> throw IllegalStateException()
is Node<T> -> this.tail
}
}
This is one of my implemented functions for filtering the sealed class list
fun <T> filter (element: List<T>, predicate:(T) -> Boolean) : List<T> = when (element) {
is List.Nil -> List.Nil as List<T> //do nothing
is List.Node -> element.tail.filter {predicate(it)}
}
I have used a working example
fun findNumbers(numbers: List<Int>, predicate: (Int) -> (Boolean)): List<Int> =
numbers.filter { predicate(it) } for a simple list
And now I am not able to figure out, why this doesn’t work with a sealed class. Any ideas?