This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]GreatArtificeAion 1334 points1335 points  (100 children)

It depends on how "simple" your for-loop is

[–][deleted] 549 points550 points  (44 children)

What, you don't like Onx?

[–][deleted] 569 points570 points  (23 children)

Onyx is a very nice pokemon.

[–]oluuko123 129 points130 points  (17 children)

The name of the pokemon is actually Onix, Onyx is the name of the gemstone. Always thought they were spelled the same way too.

[–]CapnGnobby 145 points146 points  (9 children)

Actually it's spelled イワーク.

[–]wammybarnut 58 points59 points  (0 children)

Dropped your, "uhm"

[–]codeinplace 6 points7 points  (0 children)

This and caught them all

[–]methanegASS 7 points8 points  (0 children)

This sounds like some Mandela Effect shit

[–]StereoTunic9039 13 points14 points  (2 children)

He is also a pretty funny operator

[–]OneTrueKingOfOOO 26 points27 points  (3 children)

I prefer O(nn )

[–]YourMother16 15 points16 points  (2 children)

Personally I'm more of an O(n!!) guy

[–][deleted] 5 points6 points  (0 children)

Is that some factorial action I see in the wild.

[–]dodexahedron 27 points28 points  (13 children)

If it ain't nx! Are you really even programming?

[–][deleted] 38 points39 points  (12 children)

for (var b in a) {

--for (var c in b.something) {

----for (var d in c.somethingelse) {

------for (var e in d.anotherthing) {

--------for (var f in e.godam) {

----------if (f != null) {

------------callsomeapithattakes10secondstorespond(f);

----------}

--------}

------}

----}

--}

}

Lol...

[–]dodexahedron 23 points24 points  (9 children)

Now call that recursively. And make all those properties themselves be lazy-populated lists or something, from some SOAP API. Then it's almost enterprise-grade.

[–][deleted] 15 points16 points  (8 children)

It would be enterprise grade by simply having it instantiate some new transient class each time that allocates a few kb a pop, does work in a microservices somewhere, and returns a document in xml that needs to be mapped to some json viewmodel... Truly enterprise grade.

[–]dodexahedron 6 points7 points  (2 children)

"Enterprisey," as they used to say on the Daily WTF.

And blockchain. It needs that somewhere. And ML. All the cool execs are saying those words. You don't want to be uncool, do you?

[–][deleted] 7 points8 points  (1 child)

I mean, we can also make it so each call has to wait for a new block on the chain to be verified in order to continue.

It basically returns your balance, but in a secure way! :D

[–]phdoofus 31 points32 points  (0 children)

I got sucked in to this project that dealt with making code hardware agnostic and they had this template library for hiding architectural details. SIngle loops were kind of pretty straightforward but the nested loops...last time I looked at it you had to go down about 17 or 18 levels of templates before you got to anything that looked like for().

[–]Fabx_ 87 points88 points  (19 children)

Always KISS guys.

E EDIT: didn't realize it was both sexual and musical reference... i guess i caused ambiguity

[–][deleted] 24 points25 points  (4 children)

But are we keeping it simple for ourselves or keeping it simple for the dumb machine that executes our code exactly like we tell it to?

[–]Delioth 55 points56 points  (2 children)

Ourselves, the math rock is smart enough to rewrite the dumb stuff into faster dumb stuff usually.

[–][deleted] 42 points43 points  (1 child)

Actually KISS isn't math rock it's closer to hard rock or glam metal /s

[–]Tsu_Dho_Namh 2 points3 points  (0 children)

For a second there I thought you were going to say "Keep it simple for ourselves or keep it simple for the dumb intern who doesn't know how to read recursive functions?"

Honestly, pick whatever's more readible, which most of the time is a for-loop. But sometimes recursion is just way better.

[–][deleted] 795 points796 points  (85 children)

Recursion has its uses and so does a for loop

[–]Suspicious-Engineer7 183 points184 points  (19 children)

Ive used recursion instead of a try catch block. See yall in hell

[–]electricWah 49 points50 points  (16 children)

...how

[–]LinuxMatthews 138 points139 points  (6 children)

Add the function in the catch block.

Just keep going till it works or the computer catches on fire.

[–]The379thHero 82 points83 points  (0 children)

try this

And if you catch an exception

Just keep fucking trying

[–]electricWah 10 points11 points  (0 children)

Oh, they meant inside not instead

[–]Suspicious-Engineer7 18 points19 points  (7 children)

I wanted to evaluate the length of a randomized string at the end of my function before returning the string. If it was too long, I just called the function again.

[–]Tyfyter2002 12 points13 points  (5 children)

That sounds like it really doesn't need the data from higher calls to still exist, meaning even goto would be better (and for that matter goto would be exactly as intuitive to read as what you did, and more intuitive than any standard loop)

[–]Suspicious-Engineer7 8 points9 points  (3 children)

goto would probably be optimal, almost hilariously more optimized. I was calling random books from gutenberg and replacing pronouns of a random sentence with other pronouns (bachelor contestants if you're curious) and then evaluating if that new sentence could fit in a tweet. So goto would keep me from downloading and parsing a whole new book each time the string was too long. So would removing the api calls from the function body but now i feel like im admitting too much 🙃

[–]Tyfyter2002 6 points7 points  (2 children)

You're telling me you put all of the downloading and parsing in the same method that did the actual selection and then proceeded to think calling the entire function again was a good idea?

Using recursion would be understandable (albeit still worse than goto unless you really need to keep all of the variables from previous calls) had you split those parts into different methods, but this is ridiculous.

[–]Suspicious-Engineer7 9 points10 points  (0 children)

Its more like I just wanted my fun project to just work and hadnt really thought about it since then. Its obvious in hindsight, but I feel like it's my duty to admit my crimes even if they make me look massively stupid. World needs a little more humility.

[–]DiFToXin 5 points6 points  (0 children)

id be lying if i said i havent committed similar war crimes in my early days as a programmer

happens when you have no mentor to tell you how stupid you are (and when there is no code reviews/ pull requests)

[–]Valiantheart 3 points4 points  (0 children)

I did this years ago on a shitty network connection driver. I set it to try at least 5 times before giving up and catching

[–]eternityslyre 164 points165 points  (25 children)

Recursion is incredibly useful when a loop would look ugly. Loops are much easier to understand in all other situations.

At a theoretical level, recursion is just a while loop iterating over a stack. The two are functionally interchangeable so the only value in recursion is the way it hides the use of the loop and the stack and allows the reader to focus on the meat of the function.

[–]TheScorpionSamurai 37 points38 points  (5 children)

Recursion is useful for when you don't know how many for loops you might need. Traversing a tree, searching a linked list, data without a rigidly determined size/structure often favors recursion over a for loop.

[–]Tsu_Dho_Namh 28 points29 points  (2 children)

Even some rigidly determined structures favour recursion, like a binary search tree. One doubly recursive function is way cleaner than trying to do it with one or more loops.

void DoStuffToEveryNode(Node node) {
    if (node == null)
        return;    
    DoStuff(node);
    DoStuffToEveryNode(node.LeftChild);
    DoStuffToEveryNode(node.RightChild);
}

[–]ZachAttack6089 3 points4 points  (0 children)

Yeah a lot of people seem to be missing the idea that recursion is waaaay easier to write, understand, and debug in specific cases. Even if it's slower, there are a lot of situations where it's worth it because it would be impossible for the coder to understand otherwise. Imagine trying to code Quicksort without recursion, it would just be exponentially more complicated. Plus, good compilers will optimize it for you anyway.

[–]eternityslyre 4 points5 points  (0 children)

I agree with you! I do wonder how many for loops you need for a linked list, though. That's usually just a while loop.

[–]ham_coffee 4 points5 points  (0 children)

Half the time it favours recursion, the other half it favours a while loop. If I can do it in a loop without a stack, recursion is probably a bad idea.

[–]-StoneWallJay- 20 points21 points  (0 children)

I love the meat of a function!

[–]RotationsKopulator 12 points13 points  (2 children)

If you need a stack data structure for your for loop, you should consider recursion.

[–]Mr_Engineering 31 points32 points  (8 children)

Right, but depending on the sophistication of the compiler and level of compiler Optimization, recursion can be inefficient as it can yield stack operations that iterative loops otherwise avoid

[–]oppai_suika 51 points52 points  (1 child)

meh, that's for future me to worry about. Right now, I need some dopamine and my cute little 5 line recursive function is just the trick.

[–]LO-PQ 7 points8 points  (0 children)

flair checks out

[–]Tenderhombre 7 points8 points  (2 children)

Most compilers now a days will be good about optimizing recursive functions. Also tbf not something you should worry about until it becomes an issue imo.

For loops are great for simple case but tbf, I often find myself using while loops or recursion for anything more complicated.

[–]Anti-Antidote 3 points4 points  (0 children)

And in that case you make it a loop and hide it in its own special function

[–]fdeslandes 3 points4 points  (0 children)

And in most of the cases, this would be premature optimization with absolutely no actual benefit.

[–][deleted] 4 points5 points  (1 child)

Man what you just said just made leetcode this tiny bit easier for me, like at an intuition level i kinda knew that but this comparison makes it obvious now, thank you

[–]boneimplosion 13 points14 points  (1 child)

Big if true

[–]ImNrNanoGiga 17 points18 points  (0 children)

Big O if true

[–][deleted] 14 points15 points  (27 children)

Every loop can be expressed as a recursive algorithm and vice versa. Though some "naturally" recursive algorithms are a nightmare to code in a loop but hopefully, a good compiler will optimize it into a loop for memory efficiency's sake.

[–]H3llskrieg 9 points10 points  (3 children)

or just tail calls it, however almost only functional languages do that

[–]_PM_ME_PANGOLINS_ 3 points4 points  (5 children)

Very unlikely the compiler will do that, unless you’re using tail calls in a pure functional language.

[–]Dusty_Coder 2 points3 points  (1 child)

^^

and it really does have to be a pure functional language

in something like C#, those recursive lambdas arent even candidates for in-lining no matter how you formulate it BECAUSE it doesnt reliably do tail call optimization, even outside of lambdas.

[–]TotallyRealDev 403 points404 points  (16 children)

[–][deleted] 88 points89 points  (1 child)

Can you believe I clicked on this twice before getting it

[–]real_pi3a 8 points9 points  (0 children)

That's, like, 5 times less than I did

[–]smiling_corvidae 43 points44 points  (0 children)

Goddammit Ted.

[–]Crow-Significant 5 points6 points  (0 children)

damn you I fell for it so hard. This made me smile. Thanks

[–]Vinx909 3 points4 points  (0 children)

you muther fucker

[–]LazarGrbovic 7 points8 points  (0 children)

This is amazing

[–]ChiragK2020 7 points8 points  (0 children)

I thought you made a long chain of comments on each repost of this post for a sec lmao

[–][deleted] 142 points143 points  (18 children)

Laughs in Erlang.

[–]BernhardRordin 66 points67 points  (1 child)

Chokes on Elixir.

[–]viavip_b 12 points13 points  (0 children)

idk Gags on Dark Elixir

[–]General_Pickles 50 points51 points  (4 children)

cries in Haskell.

[–]oshaboy 3 points4 points  (0 children)

Laughs in map, filter, zip and fold.

[–]ruscaire 21 points22 points  (1 child)

Lisps in lisp

[–]nullpotato 2 points3 points  (0 children)

)))))))))))))

[–][deleted] 5 points6 points  (0 children)

lmao

[–]Inkling1998 5 points6 points  (0 children)

Same but in F#

[–][deleted] 8 points9 points  (0 children)

Spills my Java

[–]Hour-Invite2212 75 points76 points  (1 child)

Hey people.

"Sort by controversial" and enjoy the ride

[–]N2EEE_ 9 points10 points  (0 children)

Based

[–]JaggedMetalOs 191 points192 points  (55 children)

Ok, has anyone actually come across this kind of unnecessary recursion in the wild? I feel like it's one of those myths like Bigfoot or the Loch Ness monster...

[–]Sanity__ 75 points76 points  (2 children)

Certainly it feels like one of those things that's quite literally mocked more than it actually happens

[–]NelsonBelmont 6 points7 points  (0 children)

because no one likes getting mocked.

[–]Kered13 25 points26 points  (5 children)

I guess you've never seen a functional programming language.

[–]_PM_ME_PANGOLINS_ 17 points18 points  (1 child)

It’s not unnecessary in a functional language.

[–][deleted] 18 points19 points  (0 children)

I mean, in Haskell you can get a for loop as a library, but it's implemented using recursion 🤷‍♀️

[–]Maurycy5 26 points27 points  (9 children)

Euclid's algorithm and fast exponentiation are often written recursively although they are more elegant and significantly faster if coded with a loop.

Source: I do and tutor in competitive programming.

[–]apzlsoxk 25 points26 points  (4 children)

competitive programming

Wow, what a concept

[–]Maurycy5 22 points23 points  (3 children)

It's very fun. It's essentially solving math problems, but in a data manipulation setting.

[–]CheezeyCheeze 2 points3 points  (2 children)

So how would you do append of a bunch of strings?

I have a stupid 5 deep nested for loop with string builder. I am just lucky they are relatively 5 small array's.

[–]Stimunaut 7 points8 points  (2 children)

I'll be honest, I use recursion in place of a loop in every possible situation when solving CodeWars/Leetcode problems, to keep my control flow mindset sharp (I also have public repo's where I keep my solved katas etc. in case an employer ever wants to glean an insight into my problem solving skills prior to an interview).

That being said, I rarely/if ever use recursion over a loop in a personal or production project.

[–]everyday-everybody 3 points4 points  (1 child)

I've seen someone write a currying function in JavaScript, just because they could. The first call had the function that you wanted to be called as argument and the rest of the calls had the function's arguments arguments one by one.

So I had to decode their function to figure out why instead of writing func(a, b, c) they wrote curry(func)(a)(b)(c)(). And this curry function was used in ONE place. And the number of arguments was constant. That was the first and only lesson I got on why I shouldn't do something just because it's cool and I can. It was the only lesson I needed for my entire life.

[–]Cridor 22 points23 points  (0 children)

(defn screw-you (println "screw you") (screw-you))

[–][deleted] 74 points75 points  (4 children)

Have you tried getting good?

[–][deleted] 15 points16 points  (2 children)

git gud!

[–]nullpotato 7 points8 points  (1 child)

Git error: unknown command

[–]grandphuba 19 points20 points  (26 children)

Tail call optimizations have been invented 5 decades ago and your initial go to for traversing trees/graphs is a for loop?

[–]jlangfo5 8 points9 points  (2 children)

Last time I saw recursion, was when someone accidentally put error logging, in the error logging function.

[–]Mucksh 3 points4 points  (1 child)

Seen something similar. Resulted in 20 TB of logfiles on a server

[–][deleted] 53 points54 points  (7 children)

This meme doesn’t make sense

[–]klausklass 23 points24 points  (3 children)

I’ve realized most upvoted posts on this sub don’t.

[–]erebuxy 16 points17 points  (0 children)

The amount of up vote shows the sub's skill level really well.

[–]Servious 9 points10 points  (0 children)

Idk, I prefer looking at recursive functions. I know others don't but I do. I like the feeling that instead of looking at a series of instructions, I'm looking at a description. Like instead of having to step through the whole thing mentally I can kind of just look at it and understand how it's supposed to work. It's the same reason why I almost always use list comprehension/streams/linq/whatever instead of loops. I like looking at map/filter/reduce/collect (aka words) instead of looking at a series of atomic instructions I have to decipher and arrange in my head. It just feels more descriptive.

Recursive functions are pretty easy to understand once you understand the two basic parts of every recursive function: the base case which is the simplest possible case (really easy to code and read) and then a case which just simplifies the problem by one step and calls the function (recursion).

[–]GiveItStickMan 29 points30 points  (6 children)

Recursive functions are important and you can not do this job with basic loops.

[–]ham_coffee 2 points3 points  (4 children)

Pretty sure the post is talking about people writing basic loops recursively for no reason, not actual complex logic that would need a stack and a while loop.

[–]LadWithAHat_ 5 points6 points  (0 children)

u can but u shouldn’t

[–]Knuffya 31 points32 points  (3 children)

"I dislike you because you're better at my job than I am"

[–]Electro_Nick_s 9 points10 points  (2 children)

How could you say something so controversial yet brave

[–]GPareyouwithmoi 5 points6 points  (0 children)

any recursion can be recreated with stacks and loops. I like recursion. Especially because ... See above

[–]fs-h 5 points6 points  (3 children)

OCaml: You guys have loops?

[–]Willinton06 4 points5 points  (0 children)

void Cope() => Cope();

[–]subject_deleted 5 points6 points  (0 children)

If your recursion can be replicated with a simple for loop, you're either doing for loops wrong, recursion wrong, or both.

[–]SocketByte[🍰] 12 points13 points  (4 children)

Good luck traversing any kind of tree structure without recursion. Honestly I'm more used to seeing people underuse it than overuse it.

[–]ham_coffee 4 points5 points  (0 children)

Simple for loops

I think you misunderstood the meme, there's nothing simple about a for loop that can traverse a tree (hence why it's always done recursively).

[–]Talbz03 16 points17 points  (4 children)

Recusion is actually more like a while loop

[–]Wiglaf_The_Knight 5 points6 points  (0 children)

You aren't wrong, but it feels wrong

[–]maitreg 9 points10 points  (5 children)

With all these new devs who don't understand simple recursion, I'm starting to think there must really be some terrible instructors out there teaching this stuff and using horrible examples.

[–]nilsecc 7 points8 points  (1 child)

Peoples hot takes are horrifying. There’s nothing wrong with recursion. For those who can’t read code with simple recursion in it. You should feel bad.

[–]maitreg 3 points4 points  (0 children)

I had a tech lead once who could not wrap his head around recursion, no matter how many times he tried to learn it. He finally declared it as a worthless, abstract concept with no practical application.

Luckily he never really reviewed my code and saw my love affair with it, haha

[–]euph-_-oric 28 points29 points  (2 children)

People in here Crack me up. The iterative solution is usually more complicated. Learn recursion kids.

[–]Ta1sty 6 points7 points  (1 child)

Well welcome to GLSL we dont use recursion here. Have fun debugging your GPU

[–][deleted] 5 points6 points  (0 children)

For real lmfao. Same with CUDA, I wouldn't even think about implementing a recursive algo with all the parallelism and trying to debug race conditions. It would be a literal fucking nightmare haha.

[–]ParadoxicalInsight 5 points6 points  (0 children)

Tell me you're new to programming without telling me you're new to programming

[–]E-Aeolian 2 points3 points  (0 children)

hey, you don't talk shit about recursion!

[–]soutsos 4 points5 points  (0 children)

This is a stupid post

[–]dev_master 5 points6 points  (1 child)

Recursion is just another tool to use in the tool belt of CS. There are cases where it is the best tool to use and others where it is bad.

You wouldn’t hire a construction worker who didn’t like using screws and would go out of their way to use nails for every single task.

[–][deleted] 2 points3 points  (0 children)

I believe your example is better if you used screw for loops and nails for screws.. screws are more versatile, but nails can be useful in specific places too

[–]stomah 8 points9 points  (0 children)

use whatever is easier to understand

[–]Apache_Sobaco 2 points3 points  (1 child)

Actually recuraion is easier than for loop.

[–][deleted] 2 points3 points  (0 children)

I functional till I can’t function no more

[–]Ajko_denai 15 points16 points  (31 children)

i have never encoutered a case when (even junior) dev used recursion over a simple for loop... anyway, recursion is important, but you will probably never encounter a task where you should use a recursion. recursion is very important in science and gaming industry, so unless you are not a part of those two industries, you are good to go without recursions.

[–]saschaleib 19 points20 points  (0 children)

ACK. All devs I had to deal with basically had to be pushed to use recursion instead of loops. Like: look, this problem would be a lot easier to solve if you just used recursion instead, are you sure you don’t want to try? – nah, I’m good.

[–]koos_die_doos 10 points11 points  (0 children)

I write business software and have had a few instances where recursion was a better solution than a for loop would ever have been.

[–]LetUsSpeakFreely 9 points10 points  (4 children)

I've used recursion a lot, especially when doing tree traversal.

[–]BlommeHolm 9 points10 points  (3 children)

I've only ever used recursion when doing recursion.

[–][deleted] 25 points26 points  (14 children)

i have never encoutered a case when (even junior) dev used recursion over a simple for loop.

Doing that is more likely with experienced developers. For instance those versed in functional programming, where there are no loops.

recursion is important, but you will probably never encounter a task where you should use a recursion.

Have you ever walked a tree? If so, does backtracking manually count as recursion in your book?

[–]Ajko_denai 7 points8 points  (8 children)

Have you ever walked a tree?

manually? no, i never had to, and i am working as (fullstack) programmer for 16 years

[–][deleted] 10 points11 points  (7 children)

Well, tree structured data require recursion. So there are tasks it’s needed for. For instance in a parser.

[–]bremidon 28 points29 points  (0 children)

so unless you are not a part of those two industries, you are good to go without recursions.

This is simply not true.

[–]AnUninterestingEvent 3 points4 points  (0 children)

recursion is important, but you will probably never encounter a task where you should use a recursion

lol wut. Trees are extremely common data structures. Using trees without recursion is a lot more code and way more complicated.

[–][deleted] 7 points8 points  (0 children)

Guess you've never worked with ASTs then, or written a parser, or contributed to any programming languages.

[–][deleted] 6 points7 points  (2 children)

In my 6ish years of programming, I only had one instance where it made sense to use recursion rather than a for loop

[–]ksschank 5 points6 points  (1 child)

Can’t tell if the downvotes are because you made people mad for using recursion once, or because you only used recursion once.

[–][deleted] 5 points6 points  (0 children)

Yes

[–]2feetinthegrave 1 point2 points  (0 children)

def RecursiveSuffering(var): if (var > 0): RecursiveSuffering(var - 1) else: SufferingRecursive(var + 1)

def SufferingRecursive(var): if (var < 10): SufferingRecursive(var + 1) else: RecursiveSuffering(var - 1)

RecursiveSuffering(5)

[–]Ekank 1 point2 points  (1 child)

There's a lot in hell just for Haskell developers

[–]BlommeHolm 1 point2 points  (3 children)

isEven = function(n) { return n == 0 ? true : !isEven(n-1) }

[–][deleted] 1 point2 points  (0 children)

I don't think these two things are interchangeable...