Search code examples
kotlindata-structureslinked-listfunctional-programmingpurely-functional

Troubles when trying to "remove by index" on a Purely functional Linked List


As the title states, I have been trying to code singly linked lists and its operations on a purely functional implementation. Things where pretty breezy up until now, lots of recursion, no modification... the works.

I then tried to implement a function to remove an element from a list, given a certain index. I can't for the life of me find a way to implement this without using a counter. It's almost like asking myself, "how to I know how many steps I have walked without myself or an spectator counting them?".

Since then I've been on a slump.

Here's the code I have so far:

    fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>?{
        if(list?.data == null){
            return list
        }
            else{
            when(index){
                0 -> remove(list)
                else -> {
                    when(listSize(list) - index){
                        0 -> {
                            return list
                        }
                        1 -> {
                            removeFromTail(list)
                        }
                        else -> {
                            TODO()//HOW?
                        }

                    }
                }
            }
        }
    }



fun <T> remove(list: ListNode<T>?):ListNode<T>?{
       return if(list?.data == null){
            list
        }
        else{
            list.next
        }
    }


fun <T> removeFromTail(list:ListNode<T>?):ListNode<T>?{
        return if(list?.data == null){
            list
        } else{
            when(list.next){
                null -> null
                else -> {
                    ListNode(list.data, removeFromTail(list.next))
                }
            }
        }
    }

Thanks a lot in advance for your help and input.


Solution

  • Easy peasy:

    fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>? = when {
        list == null || index < 0 -> list
        index == 0 -> list.next
        else -> ListNode<T> (
            list.data,
            removeFromIndex(list.next, index-1)
        )
    }