A previous tip stated that RPG does not allow recursive calls. Actually ILE RPG does allow recursion. A program cannot call itself, but it can call a subprocedure that calls itself.
The procedure call should not use the CALLP opcode, rather it should use the EVAL opcode and treat the procedure as a function. For example, a procedure name CALCS would use the following code:
The sample code calculates the n'th number in a Fibonacci sequence. A Fibonacci sequence is a sequence whereby any number is equal to the previous two numbers in the sequence:
Nbr(n) = Nbr(n-1) + Nbr(n-2).
In the sequence, the first number is 1, preceeded by an implied zero so that the second number has an "n-2" to use.
The first few elements then calculate to:
1 1 2 3 5 8 13 21 34
It is an interesting exercise to run this procedure in DEBUG and observe its action.
The subprocedure CALCS would be called from an ILE RPG program using a statement such as:
EVAL RESULT = CALCS(Nbr)
Note that if the recursion proceeds through too many recursive calls, that performance drastically slows down. In this example, anything over 30 calls really ran slowly. If the job ends abnormally while into a deep call stack, the end job process takes a very long time. Because of this, I cannot think of many practical applications of recursion in ILE RPG.
* Procedure Prototype DCALCS PR 9P 0 D 9P 0 * * * * * * * * * * * * * * * * * * * Procedure Definition P CALCS B * D CALCS PI 9P 0 D NBR 9P 0 * * Procedure variables D NM1 S 9P 0 D NM2 S 9P 0 * C SELECT * Endpoint if inbound parm = 0 C WHEN NBR = 0 C RETURN 1 * Endpoint if inbound parm = 1 C WHEN NBR = 1 C RETURN 1 * Endpoint if inbound parm = 2 C WHEN NBR = 2 C RETURN 1 * Recursive call C OTHER C EVAL NM1 = NBR - 1 C EVAL NM2 = NBR - 2 C RETURN CALCS(NM1)+ CALCS(NM2)
MORE INFORMATION ON THIS TOPIC
The Best Web Links: tips, tutorials and more.
Ask your programming questions--or help out your peers by answering them--in our live discussion forums.
Ask the Experts yourself: Our application development gurus are waiting to answer your programming questions.
Search400's targeted search engine: Get relevant information on RPG.