r/computerscience • • May 03 '21

When to use recursion?

/r/computerscience/comments/n3kjbf/when_to_use_recursion/
161 Upvotes

13 comments sorted by

•

u/kboy101222 Computer Scientist May 03 '21

God damn you, OP. I looked at this and about lost my mind trying to remember if I'd already approved this. Then I click through the link and it's on this sub. I about lost my mind trying to figure out wtf was going on before I realized...

→ More replies (4)

33

u/QuantumFTL Researcher May 04 '21

This is the only kind of CS shitposting I can get behind.

Bravo, u/John_Mansell, bravo.

4

u/[deleted] May 03 '21

Oftentimes I want to implement a n-sized nested loop, with n being a variable that changes. That's one common instance where I just use recursion.

10

u/John_Mansell May 03 '21

I crossposted the question "When to use recursion" from r/ComputerScience to r/ComputerScience ... because that's funny to me.

I appreciate the response, but it'd probably be better served on the post which was actually asking the question. I've added your response to the original question.

7

u/[deleted] May 03 '21

I can't believe I missed that. Now I see what you were going for lol

1

u/John_Mansell May 03 '21

Thanks. Lol. It made me laugh. Probably would have been better to repost it as a response to the original question. By posting it as its own question I think most people are missing it. I thought they'd see that it was x-posted, but that's a pretty small detail and easily missed.

Well, if I got one other person to chuckle, I'm happy with it.

7

u/[deleted] May 04 '21

.....oh

Well done

14

u/olagirosougirizoun May 03 '21

In with most programming languages implementing tail recursion and your typical for loop makes no difference due to some translation done when you compile your code. You might get stackoverflow exceptions when using it with large parameters (using linear non-tail recursion or anything more complex than that) so i guess for loops are the way to go. You have to appreciate though that desinging a recursive function is sometimes easier that a loop (having to define 3 + variables ). Recursion makes it very easy to prove programs by induction if you are into these kind of stuff. Recursion is also vital in functional programming languages (Haskell, Scala), and i would say there is also the idea of recursion in logical programming languages as well (ex Prolog)

6

u/berrmal64 May 03 '21

A classic example is if you don't know how many iterations you need, or have nested operations on identical things, like traversing a tree or graph.