
-----------------------------------
J-son
Thu Aug 28, 2014 5:16 pm

Using a procedure's code to call itself
-----------------------------------
How does the logic work in a procedure calling itself?

Ex. 

proc MainProgram (var Number : array 1 .. * of int)
.. snip ..
Main_Program (Lowest)
.. snip ..
end MainProgram

It doesn't seem to make sense to me but my code succeeds.
I don't understand how the procedure can call itself before it ends. 

It sort of seems like once the computer reaches the procedure call it goes back up and starts running the procedure again and again..

-----------------------------------
Zren
Thu Aug 28, 2014 6:58 pm

RE:Using a procedure\'s code to call itself
-----------------------------------
Welcome to the lovely world of recursion.

Scroll down to you get to the recursion section.

http://compsci.ca/v3/viewtopic.php?t=14665


Edit:
As for how it works. Defining a function normally would be the equivalent of using  and . Forward is used to define the function's signature (the name of the function, how many arguments it has, and the data type of each of those arguments).


forward function add(a: real, b: real)


Body is used to define the, well, body of a function.


body function add(a: real, b: real)
    result a + b
end


So:


function add(a: real, b: real)
    result a + b
end


is the same as writing:


forward function add(a: real, b: real)
body function add(a: real, b: real)
    result a + b
end


Which means you can reference itself since it's already defined.

-----------------------------------
Raknarg
Thu Aug 28, 2014 9:27 pm

RE:Using a procedure\'s code to call itself
-----------------------------------
Yup, as Zren said, this is known as recursion, and can be quite useful.

It's not any different from calling a function inside another function. The only difference is that here you're calling the same one over and over again.

For instance, try and figure out what this does:


proc recursiveProcedure(n : int)
    if n = 1 so skip 'if' code
y = { % pause this function to open another
- - x = 2 % a new local variable that has nothing to do with the original x
- - x >= 1 so skip 'if' code
- - y = {
- - - x = 1
- - - x >= 1 so skip 'if' code
- - - y = {
- - - - x = 0
- - - - x < 1 so run 'if' code
- - - - - result 0
- - - } y = 0
- - - result 0
- - } y = 0
- - result 0
} y = 0
result 0 
(i didnt use code tags so that i could colour-code the different layers)
so as you can see, once the inner function closes, execution resumes from the point it left off until there are no more functions and it returns the final answer
