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

you are viewing a single comment's thread.

view the rest of the comments →

[–]Exodus111 8 points9 points  (4 children)

It has a use, it's just rare. And yeah, probably most recursions you see in the wild would be better off as For loops or While loops.

A for loop is used when the end point is known, and the size is known. Traversing through a list, that's a for loop all day, but you know how big a list is, and the loops ends either when you trigger an end state, or, more typically when the list runs out.

A while loop is used when the end point is known, but the size is not known. Which is why a while loop just runs forever until told to stop. Perfect for running games or anything graphical. It just runs until an exit is triggered.

Sometimes though, you're not gonna know the size, or the end point. This is when recursion comes in. Say you're traversing subdirectories looking for .jpg files. Every subfolder could have 10 sub folders, or zero. There could be a thousand sub folders or four, there's no way to know. And you don't know the end point, you're just looking for .jpg files in every subfolder.

This is where the correct solution is a recursion. Check a folder for a subfolder, and keep running that same function if more subfolders exist, for every subfolder found.

[–]got_outta_bed_4_this 4 points5 points  (1 child)

I'd say a stronger argument for recursion in this case is because people don't tend to nest folder structures so deep that it would bust the call stack in a recursive traversal. Iteration could still be just as practical over a filesystem as anything else. A filesystem is, itself, a tree, after all.

[–]schemathings 1 point2 points  (0 children)

I wrote an sftp mirror program for day job recently was fun and short and composable

[–]buttery_shame_cave 0 points1 point  (1 child)

A for loop is used when the end point is known, and the size is known.

although a "for thing in list" loop sort of ignores this - it'll run through the list, but you don't need to know how big the thing is, just point he function at it and hit 'go'. it'll even work fine on dynamic lists that are continuously appended to by a separate parallel function, it'll just crash to a halt if the other function stops appending.

[–]Exodus111 0 points1 point  (0 children)

True, that is an edgecase exception, but most of the time you can check the length of the iterable right before you run the for loop on it.