Recursion: Functions
Recursion: Functions
Functions are basically the best. Like the name suggests, without them, code wouldn't be able to function.
Or. it would, it would just be much harder to read and change. Which is as good as non-functioning the minute an operating system update makes something break.
Anyway. A function is a named piece of code that can be run at any time in a program or script. When the code hits a function in a program, it jumps out of that line and into the body of that function. Once the function has done its business, it heads back to wherever the computer was in the calling code.
It's like a conditional…except without the condition.
Whenever you ask the computer to print to the screen in a program, chances are you're calling a function that does all the dirty work of painting the letters to screen for you. Unless the language developer really likes watching coders suffer (which sounds like a form of masochism, if you ask us), they abstract away from all the lines of code it takes to actually make those words show up on the screen.
(Trust us, there are a lot.)
Here's a basic function.
FUNCTION add(int x, int y) { DEFINE sum = x + y RETURN sum END FUNCTION
This fuction isn't particularly important in the scheme of things, but it lets you call it anywhere in the program—whenever you want to add two numbers together, in fact.
Most languages have a way of returning data after the function finishes doing its…functioning. That's where recursion comes in.
To turn a function from a completely normal, run-of-the-mill subroutine into a infinitely repeating monster recursive call, the function has to call itself before ending.
That's it.
To turn that add()
function recursive, you'd write something like this:
FUNCTION add(int x, int y){ IF y == 0 RETURN x ELSE x = x + 1 add(x, y – 1) END IF END FUNCTION
If that looks inefficient to you…you'd be right. If you think it still adds x
and y
…you'd also be right. If you thought it was recursive…you'd be right again. (You're really good at calling these things.)
Because the function itself calls itself (see the fifth line of the function), it's magically recursive. It also will end before running infinitely.
But more on that later.