HyperactiveSeagulls HyperactiveSeagulls - 1 year ago 187
Brainfuck Question

Example of a recursive function in brainfuck

Straight to the point - I've been learning brainfuck, but I'm having trouble getting round the idea of recursion in it. I've googled for this and searched the forums - so apologies in advance if needed - and come up with nothing.

First of all, is it actually possible?

If so, are there any examples? I'll add in anything useful I can come up with.

I'm specifically trying to work out the Fibonacci numbers using recursion, so it'd help a lot if we could base it on that.

Answer Source

Since BF doesn't really offer anything other than a tape and a pointer and VERY basic looping capabilities (typically you need to ensure that the pointer ends up in the same place as it started, what are called balanced loops. In rare cases you can do loops without them being balanced such as arrays), it is quite difficult to implement recursive algorithms in it. You may try to simulate a "normal" computer in bf (it all depends on how you treat the tape). I believe the C2BF project works this way (it compiles C to brainfuck). If I'm not mistaken they treat groups of cells in alternating pairs of stack/heap (making certain pointer operations a bit different, since everything has to be multiplied by 2)

So, after all this text here's my conclusion: It IS possible to implement recursive algorithms in brainfuck although it is really difficult. What I urge you to remember is that every recursive algorithm can be done iteratively. You just have to maintain your own stack. This is actually what you will end up doing anyway if you want to implement it recursively. But if you think about it as being iterative and maintaining your own stack, instead of recursive, it will help you understand what you are actually doing and ultimately result in a better designed algorithm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download