About recursion and how to avoid mutation

What happens

I’m solving the challenge 49 of codeabbey. After hours trying to solve the problem without using iterative structures a new issue arrise; we must avoid mutation.

Mutation is basically declaring a variable and overwrite it later.

I’m not an advanced programmer so the main purpose of this post is try to understand: How avoid mutation?

What do you understand or find about that problem

After fixing a simple mutation case in my code, I send the commit again, and this time, was found more mutation problems.

I think that in challenges where you must use recursion everywhere and track the result of a variable, would be almost impossible (at least for me) to avoid mutation, because you must update the variable and enter it again to the function (in the recursion ).

You make any workaround? What did you do?

At this point I don’t see any way to solve that issue, maybe with another 10h of searching, but I encourage the forum to help us with this kind of issues that probably will arise again to others parterns.

Evidences

https://gitlab.com/autonomicjump/challenges/-/merge_requests/8192#note_639161278

I need help with

Would be really helpfull understand how avoid mutations. And is not about just defining functions, because all that functions must be recursive, and when you are imbibing one function into another into another, into another … the logical starts to get really hard.

Maybe you are misunderstanding something?, the simplest idea is avoid reuse variables, keep them as constants, instead of that you can reuse functions.

This is what you do in a “while” or “for” loop, but this loops normally mutate vars within them

You can see the following fragment, you can do the same with a for loop but here we reuse the function and the variables do not mutate

def printer(var):
  if var != 0:
    print(var)
    printer(var - 1)

printer(10)

I recommend you read about tail optimization from my point of view this reduces that complexity of recursive calls apart from its other advantages.

1 Like