I am practicing some functional programming with a sealed class List and a map function.
So far the code for the sealed 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
}
}
The map function inside the sealed class worked fine, but now I want it to run outside the sealed class like
fun <T,R> map (list:List<T>, f: (T) -> R) {
when(list) {
is List.Nil -> List.Nil as List<R>
is List.Node -> List.Node<R> (f(head), tail.map(f))
}
}
But now "head" and "tail" don't work any longer, because of unresolved references. I tried different strategies, but nothings works. Any ideas how to solve it?