r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

105

u/NewInHere__ Apr 05 '22

recursion, just... recursion

71

u/dkToT Apr 05 '22

Basically a function that will call itself until a certain criteria or situation is satisfied. Once it is satisfied, the result will be returned to the parent function call all the way back to the top. This will help with clean code but only if you know your functionality follows a certain pattern.

A great example of this is the fibonacci series and why it was used in alot of early interview questions. The fib(n) is equal to fib(n-1) + fib(n-2). With recursion you can use this pattern to do the calculation for fib(n-1) and fib(n-2) where fib(n-1) = fib(n-2) + fib(n-3) and fib(n-2) = fib(n-3) + fib(n-4), etc....

Super useful and clean if you now the exact pattern and expectation (traversing a tree, etc..) of what you are building but I personally don't see this used often.

15

u/TheTomato2 Apr 05 '22

To add on to this, recursion, at least for me, was confusing because sometimes it's taught before they teach you how or what the main stack in program works/is. It's really simple once you learn its just the same function calling itself and pushing another instance on to the stack and then using returns to unwind the stack. That's all recursion is. It's also makes it easy to understand why probably shouldn't use it unless the problem really begs for it.

4

u/above_all_be_kind Apr 06 '22

Yes, this was exactly it for me. Recursion, as a concept, was perfectly understandable but it wasn’t until I understood how its code-based implementation actually worked that I was able to start getting comfortable with creating it from scratch. The whole secret to understanding its code-based implementation, as it turned out, was comprehension of stacks.

7

u/Temporary-Warthog250 Apr 05 '22

Awesome!!

5

u/---cameron Apr 05 '22 edited Apr 05 '22

Recursion:

GNU means GNU is NOT UNIX

It is defined in terms of itself.

add(x,y)
  return add(x-1,y+1) + 2 

uppercase_name(name)
    uppercase_name(first_half(name)) + uppercase_name(second_half(name))

Of course, in these versions the functions / GNU are purely defined in terms of themselves, so they'd go on forever; (GNU) = (GNU is not linux) = ((GNU is not linux) is not linux) = (((GNU is not linux) is not linux) is not linux) ....

So I just want to add that while recursion implies a loop, you want to eventually have a way to end the loop, by making the definition at some point not call itself (as if it calls itself, it starts the loop again)

add(x,y)
    // During one of our 'loops', when we finally meet this condition
   // we don't loop again, we will finish
    if(x <= 0)
      return x + y;
    else
      return add(x-1,y-1) + 2  

(Note, this add function is weird, its just an arbitrary example of defining something in terms of itself).

So calling add would result in

add(3,1)

 // x isn't = 0 so 

--> add(2,0) + 2

--> (add(1,-1) + 2) + 2

--> ((add(0,-2) + 2) + 2) + 2

 // X is 0 so we just return x + y 

--> ((0 + -2) + 2) + 2) + 2

--> 4

2

u/TeknicalThrowAway Apr 05 '22

of what you are building but I personally don't see this used often.

Traversing a filesystem, or a DOM, or parsing a document :)

2

u/[deleted] Apr 06 '22

I can understand that Recursion repeats itself. but every code repeats the process it is doing, all the for/while loops that i have used in code is also repeating. so does that mean, i can apply recursion to every program ??? or is there any limitation ??

2

u/username-256 Apr 10 '22

Good question. The answer is to do with how recursion is implemented.

While recursion is in theory equivalent to iteration, since every recursive algorithm can be implemented by an iterative algorithm, in practice recursion nearly always uses more memory. The extra memory is used when the implementation adds data (such as the function return address) onto the machine call stack. The data can also include the call arguments (the values you pass to the function parameters).

In some languages and some compilers a version of recursion called tail recursion can be used (or recognised by the compiler) where extra data is NOT added to the stack.

So no, you shouldn't apply recursion to every problem. Real-world problems such as limited (virtual) memory get in the way. Meaning that after MANY recursive calls your program crashes with an "out of memory' condition.

→ More replies (3)

101

u/Emerald-Hedgehog Apr 05 '22 edited Apr 06 '22

Alright. Imagine you got a steak and you wanna cook it well done. It's needs to be cooked 5 minutes for that.

Function CookSteak(🥩)
{
   🥩.CookedMinutes += 1

   If (!🥩.IsWellDone()) { return CookSteak(🥩) }
   else { return 🥩 }
}

Does this help?

49

u/KrafDinner Apr 05 '22

I'm not sure if it helped the asker or not, but it's a fantastic explanation... and steak... mmmm

36

u/WarWizard Apr 05 '22

Why not just call this function BurnSteak() or MakeSteakInedible()

:D

14

u/_Personage Apr 05 '22

function cookShoeLeather()

Yeah, that was the last time I made any sort of meat for the person who called my meat tacos that :(

2

u/ballbeamboy2 Apr 05 '22

>!🥩.isWellDone()

Could be understood as !CookedMinutes == 5 which mean if the steak's cookeMminute is not equal to 5 then continue cooking, and once cookedMinutes is 5, return the steak and recursion will stop calling because. the exit condion is when cookedMinutes is 5

→ More replies (1)

2

u/OfJahaerys Apr 05 '22

Also, if you speak another language, most European languages have something called a reflexive verb. It is the same thing as recursion just as a string ;)

"Je m'appele" in French is an example. It folds back on itself.

→ More replies (2)
→ More replies (1)

12

u/MyHomeworkAteMyDog Apr 05 '22 edited Apr 06 '22

Just to add, here are the elements of a recursive algorithm:

  1. A base case, when the algorithm returns an answer without further recursion.

  2. A recursive call, to a smaller subproblem closer to the base case.

  3. A way to accumulate the recursive solutions

20

u/AlSweigart Author: ATBS Apr 05 '22

I just got done writing an entire book on recursion.

Recursion is tricky, but mostly it's just poorly taught. The main thing that instructors fail to talk about is the call stack. It's the invisible data structure that automatically handles where the execution should return as you call and return from functions.

Once you know that, and you can see that local variables are local to the function call and not just to the function, it becomes a bit easier to see how recursive functions work.

It's tricky though, because you can't point to the call stack in your source code. Without having that explicitly pointed out, recursion just seems like magic. But it isn't magical or somehow more powerful: *literally anything you can do with recursion you can do without recursion by using a loop and a stack. It's just that recursive algorithms use the (unstated, hidden) call stack as their stack.

(I always get people saying, "some things do require recursion" and, no, they don't require it. Here's a non-recursive Python implementation of the famously recursive Ackermann function, and it has the same output as the normal recursive one.)

It's fine to have difficulty with recursion though; recursion is overrated and often a terrible way to write code. The times when recursion is useful is for problems that involve a tree-like structure and some sort of backtracking (maze solving, tower of hanoi, etc). Otherwise, iterative code is much simpler and I think some programmers just use recursion because it makes them feel smart.

6

u/flank-cubey-cube Apr 05 '22

To add on to your last paragraph, recursion also incurs some overhead and isn't the most efficient way to do things. Each function called recursively gets added to the stack frame, and if you have an *extremely* large tree structure, you'll get a stack overflow. The exception to this is if you are able to optimize for tail recursion, because than the compiler will be able optimize it to a loop.

9

u/AlSweigart Author: ATBS Apr 05 '22

Yes, but I always hold off on performance claims until I run code under a profiler. I've had some recursive code end up being faster than an iterative version. (Not sure how that happened.)

Also, to be specific, the stack overflow happens if you have an extremely deep tree. Like, it could be a linked list (which is basically a unary tree) that is a couple thousand nodes long. If you had an extremely large but shallow tree, you won't have a stack overflow.

And many interpreters/compilers don't have tail call optimization, including the main ones for Python, JavaScript, and Java. I hold the opinion that tail call optimization should never be used.

All recursive functions can be implemented iterative using a loop and stack. If you are doing tail recursion, it's because your recursive algorithm doesn't require the call stack. So iteratively you can implement it as a loop and a stack without the stack, so why not just use a loop? Often times you have to mangle the code and decrease readability to make it tail recursive, so I'd just go with a simple loop every time.

I can't think of a tail recursive function that wouldn't be improved by just using a loop.

→ More replies (1)
→ More replies (2)

4

u/EdenStrife Apr 05 '22

It's just calling a function from within itself.

It's sometimes easier and makes more sense than doing a loop.

9

u/KimPeek Apr 05 '22

There is high risk of introducing memory leaks if you use recursion where you should use a loop. They are not interchangeable. CS recursion, compared to mathematical recursion, requires more than a function calling itself. Recursion requires a base case, a decomposable problem (size-n problem), a defined subproblem (size-m problem), and the construction of the solution for the size-n problem from solutions to size-m problems.

3

u/EdenStrife Apr 05 '22

Sure, recursion is not a substitute for a loop in all cases. It's useful for specific problems.

I do have a bit of an issue with defining recursion the way you do. Recursive problems and their solution structure is one thing and recursion as a concept seems to me to be different things.

The idea is just that a function calls itself. That you can use that to solve a specific kind of problem seems to me at least to be an arbitrary add-on to the definition.

4

u/KimPeek Apr 05 '22

Right, but "a function calls itself" is an oversimplified description, not a definition of recursion. It reduces recursion down the point of being useless and is probably why people struggle with applying it. It doesn't help anyone in this thread who doesn't know how to apply recursion to solve a problem.

The definition I gave is not mine. It's from Robert Sedgewick who is the author of one of the most widely used Data Structure and Algorithms books. Page 25 of Algorithms Fourth Edition, halfway down the page. I'm also not the only one to use this definition in this thread.

3

u/EdenStrife Apr 05 '22

It reduces recursion down the point of being useless and is probably why people struggle with applying it

Sure, i just disagree that the definition of a term should also include a tutorial on how to use that thing in practice.

Plenty of other places use the more general definition of just being a function calling itself.

It's as if a wheel could not be referred to in isolation but only as a part of a holistic transport solution. Like the wheel would have no name if not attached to a car.

Figuring out how to use a thing, and what that thing is don't have to be connected, i think.

→ More replies (3)
→ More replies (2)
→ More replies (2)
→ More replies (17)