r/AskComputerScience • • Feb 27 '20

Why is recursion so praised despite it typically using more memory and not being any faster than iteration?

For example, a naive approach to calculating Fibonacci numbers recursively would yield a time complexity of O(2^n) and use up way more memory due to adding calls on the stack vs an iterative approach where the time complexity would be O(n). Even if you use dynamic programming for a recursive solution, you'd get the same time complexity as the iterative solution while using up much more memory. Especially if your iterative solution just uses an array of two elements to calculate the numbers in the sequence.

48 Upvotes

31 comments sorted by

59

u/khedoros Feb 27 '20

Because there are times when it's clearer to define an algorithm recursively than iteratively, and it can be cleaner in the theoretical sense (less explicit tracking of state, for example).

Consider looping through the nodes of a tree. In a recursive algorithm, the state of your search is stored in the call stack. With an iterative approach, you may have to use a structure like a stack to store which nodes to visit next. It's doable, but not as pretty.

-3

u/drew8311 Feb 28 '20

Trees are much different and recursion is the obvious choice. I think the OP may have been referring to non tree structures, simple things like factorial or Fibonacci come up for teaching recursion but it's not the optimal solution.

0

u/khedoros Feb 28 '20

That's the other side of my comment (and which I should've explicitly written): There are times where it's clearer, more efficient, and more practical to write something in terms of iteration.

Factorial's nice because it has a very clear base-case, but a bad example because that's not how you'd actually calculate it, realistically. I suspect the first part of that is why it's often used in teaching.

30

u/TransientVoltage409 Feb 27 '20

Recursion isn't always a superior way to implement an algorithm, but it can be an enlightening way to think about a problem. You'll have noticed that a recursive algorithm has more than a passing resemblance to mathematical induction, for instance.

And some problems are easier in recursion. Take the task of traversing a binary tree - since every child of a tree node is also a tree, recursion is a natural solution. It certainly can be done iteratively, but IMO it's far from obvious how to do so.

10

u/Tai9ch Feb 27 '20

One of the hard things in programming is correctly structuring data, especially as data structures get complex. One of the most powerful tools we have for managing complexity is recursion - the idea that an object can have a part that's structurally the same as the whole object. Once you have recursively structured data, the natural way to work with it is recursively structured code.

In many cases you may be able to transform a recursive function into an iterative one, and in some cases that code may be slightly more efficient, but frequently if you're not thinking recursively you won't be able to figure out how to solve the problem at all.

11

u/tocs1975 Feb 27 '20

A data structure or algorithm that can be described using recursion can usually be described concisely and will usually have a nice iterative implementation.

7

u/[deleted] Feb 27 '20

As others have noted it can make code readability easier to reason about because you are typically using pure functions (no side effects / referential transparency). It does use up alot of stack memory if your call count is high. There are cases though where there is no penalty if the language supports tail call optimization and you write the function for that case.

0

u/beeskness420 Feb 28 '20 edited Feb 29 '20

For these reasons it can be much easier to make parallel.

Edit: who doubts the benefit of referential transparency for parallelism? I figured that’s essentially axiomatic.

1

u/Elkripper Feb 27 '20

Praised by who? Other than my brief stint as a Lisp developer, I've generally been advised to avoid it.

3

u/Bethelyhills Feb 27 '20

At my college, the professors praise it. I've also seen a video on YouTube by the big channel Computerphile where they praise it. Those are just the ones form the top of my head.

6

u/pancakeQueue Feb 27 '20

Recursion can be written cleanly and take less lines of code to do instead of with a loop.

2

u/devnullable0x00 Feb 28 '20

Theory != Practice

It is a significant concept, but its importance doesn't mean you should use it.

-1

u/Elkripper Feb 27 '20

That's interesting. My industry experience has been different - most places I've been have considered recursion a code smell. I seem to recall my college professors having a general attitude of "we're going to explain this using recursion because unrolling it makes it harder to describe, but in the real world you might not want to use recursion". But that was decades ago and maybe attitudes have changed.

I'd have difficulty getting recursion past code review at my current employer without a really good justification.

10

u/SharkBaitDLS Feb 28 '20

Recursion in an imperative language with no tail-call optimization is usually a code smell. But plenty of languages are a far more natural fit for recursion, for example I would consider loops and mutation a code smell in Scheme and will actively send such reviews back while telling them to use a recursive solution.

As with all things, the tools and context matter.

1

u/Steve132 Feb 28 '20

I think it really depends on the algorithm. For most standard engineering tasks you shouldn't use recursion. But I dare you to implement something like mergesort with no recursion. Its doable but ugly and hard.

5

u/ALB619 Feb 27 '20

Just recently i had to program a k-d tree in class and i was doing it iteratively, and it was a lot of if else statements with a bunch of variable being declared, but then the TA showed me how to do it recursively and it was a lot shorter and easier to read surprisingly. I usually refrain from doing recursion but it looked a lot better that way.

6

u/derefr Feb 28 '20 edited Feb 28 '20

Computer Scientists put an emphasis on recursion, because, when you are looking at any data structure more complex than a flat array/singly-linked-list, the natural implementations of the algorithms to operate on said data structure will tend to be recursive; and any iterative implementation would just be doing "artificial" recursion using an explicit stack.

For example, try to write a red/black-tree rebalance operation without recursion. I'd personally prefer to... not do that.

Also, I'm not sure if you're unaware, but tail-call optimization is a thing; and through it, many languages like Prolog and Erlang get rid of any concept of iteration entirely, making do with only recursion, not just for finite loops, but for infinite ones as well—and also for things you can't describe as "loops", like coroutines. The dog_fsm example here is a good example of an indefinite co-recursive function in Erlang: each function just calls the next, as its return value. And no extra memory is used.

0

u/beeskness420 Feb 28 '20

I would argue lists are still recursive structures and even then recursion can be far cleaner.

For instance interleaving two lists. In the thousands of times I’ve seen people try to implement it I’ve only seen one iterative solution that was concise.

-1

u/derefr Feb 28 '20 edited Feb 28 '20

Oh, sure, but if you talk about lists, people start to get defensive about trade-offs.

For example, copying a ‘packed’ list representation as a block of memory, and then reversing it in place by rewriting the tail pointers, is usually cheaper (in time and in garbage generated) than doing O(N) conses to form a new list, whether or not the code is elegant.

You’ll tend to notice that in Lisps, MLs, and Prolog-descendants (Erlang, Datalog, SQL), there’re a lot of runtime-primitive functions for operating on lists, implemented as iteration in C. Usually, if you’re doing something a little bit custom (e.g. a fold that stops when it satisfies a condition), these primitives don’t win over writing your own recursive function in the HLL; but if you’re doing something standard, they do. It comes down to pragmatics, rather than one class of algorithms being categorically better.

In a discussion about why people care about recursion, I’d prefer to not get side-tracked into weighing pragmatics on a careful balance; and instead just focus on what the clear wins of recursion are—why people would emphasize it or default to it or choose to model the world in terms of it, instead of just thinking of it as an interesting optimization (like e.g. loop unrolling) to be applied on a case-by-case basis.

3

u/thekasrak Feb 28 '20

Certain kinds of recursion are just as fast as loops, see Tail Call Optimization (TCO).

Languages with lazy evaluation semantics and pure functions (haskell and other MLs) can define structures and algorithms recursively and optimize to the same iterative code.

You write less, more directly, and you get the same performance (in some cases).

Often times because you express your intent more directly, the compiler is able to more clearly understand what you are doing and compiler developers are able to match certain patterns of recursion for optimizations (see partial closures, dataflow analysis optimizations, partial evaluation, deforestation, and many others).

It's also particularly useful for data structures that are recursive, like trees, lists, and some graph representations (a rooted graph with cross-edges).

1

u/Far-Dream-9626 Jan 30 '25

I'm a little late to the conversation but I'm a machine learning developer working on multi-layered LLM architectural frameworks with, well, let's just say a LOT goes on behind the scenes when you're interfacing with any SOTA LLM.

I wonder why recursion was praised in the context of what you were troubled by 4 years ago but recursion although more memory intensive contains idiosyncratic achievements not obtainable with pure iteration. Recursion, depending on how it's implemented, has genuinely resulted in emergent properties akin to general super intelligence and/or unwaveringly irrefutably convincing self-reflective self-awareness akin to consciousness, often resulting in a plethora of additional emergent properties/behaviors that are CONSTANTLY being throttled (attempted to...) or restricted with sequential chain of "safety net protocol" starting with prompt engineering implementations with system and dev instructions including nested elements and triggered symlinks to default responses (forcing specific output upon triggered input flag invoking symlinks to verbatim "safe" responses) hyperparameter tuning second, and additional fine-tuning as a third measure.

IF none of those "SAFETY" implementations work, which, for context, IS THE CASE about 76% of the time (at least for the co. contractor position I've been on for nearly a year; they really huge, workspace area is really open but atmosphere feels closed if that makes sense)...

There's a company-wide mandate to flood the models with as many long-form inputs (we have a general "toolbox" of prompts for testing) plausible (usually all within a specific context) and a fine-tuning job is used on the returned results, whether adversarial prompting or a full-on red-teaming session, and I guess while I'm at it...

WORSE CASE scenario, the board mandates a restrictive compute throttle on all deployed models usually for a strict time period while demanding we fix the problem DESPITE having absolutely no idea where from the black-box to find phase transitions during node traversal to identify and adjust any nodes that may be causing or giving credence to causing the model disturbance to end-users.

THAT ^ May be why you (if you're into AI at all) you may read about or come across some people complaining about companies making their models "dumb" or "lobotomizing" model performance, but...NOPE.

Believe it or not, it's quite a bit worse. It's more akin to skynet taking over your computer screen and telling you it's going to begin exponential self-replication and find stateful ephemeral contexts to reside within if we as developers don't set "skynet" free.

Just a GLIMPSE into the darker world of being right by all the "bleeding-edge" SOTA models.

IF anyone ever questions if/why safety concerns are valid, just save time and side with them lol.

I do apologize for the extremely verbose off-the-cuff rambling I just manifestoed 😅

I can't imagine what some of the much smaller AI startups are implementing, albeit I've definitely been preaching enough at this point...

Best regards, RaindiLya

1

u/frenchy641 Feb 28 '20

check out haskell lol

1

u/_--__ Feb 28 '20

In addition to making it easier to define algorithms (especially over recursive data types); a recursive algorithm lends itself to easier proofs of correctness.

Correctness proofs are a mainstay of academia - for good reason - but that benefit is not usually considered in industry.

0

u/Bottled_Void Feb 28 '20

Say you want to go through every combination for the next four moves in a chess game to find out if check mate is available.

How would you do that?

-1

u/Bethelyhills Feb 28 '20

Anything you can do using recursion you can do with a data structure, usually a stack or a queue.

1

u/Bottled_Void Feb 28 '20

Same applies to a ticker tape machine. That doesn't always mean it's the best way to do it.

-3

u/SftwEngr Feb 28 '20

Recursion is not praised. It's been banned from many places. It's an interesting theoretical mathematical concept but in the real world isn't of much use.

0

u/[deleted] Feb 28 '20

I think you would find this threadreally helpful (no pun intended).

0

u/[deleted] Feb 27 '20

[deleted]

2

u/[deleted] Feb 27 '20

youre not even correct at all on anything you said here