23
Sat, Nov
1 New Articles

TechTip: Some Uses for Recursion

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

You've all read about recursion by now, but have you found uses for it? I'm going to discuss a couple of uses I've found.

What Is Recursion, Again?

With the number of articles written about recursion out there, I'm not going to get deeply into what it is. Here is a brief overview:

There are two types of recursion: Direct recursion occurs when a program or procedure calls itself. Indirect recursion occurs when a program or procedure calls another program or procedure already running higher up in the invocation stack, thus starting an additional invocation of the called program. For example, Program A calls Program B, Program B calls Program C, and Program C calls Program A.

So What's It Good For?

The articles you've read usually touch on two applications for recursion. First, of course, is the classic factorial problem. A recursive definition of n! is n * (n-1)!. Within a Factorial subprocedure, this would result in a recursive call:

return n * Factorial(n-1);

Then, for a business application, the articles exemplify Bill of Material (BOM) explosion. As a BOM procedure is listing the components of a product, recursion is used to explode the components of a component.

So what else can recursion be used for? Well, here are two ways we use it at my shop.

Direct Recursion and Nested Lists

We have an automated email system. Various programs generate email and then call an emailing program to send the email to a primary recipient. These programs may also send a name of a distribution list of carbon copy recipients. A distribution list contains a combination of actual email addresses, vendor IDs (the emailing program will go to the vendor master to get the address), and/or special instructions for deriving a recipient. The emailing program will send the email to those recipients listed in the distribution list.

Now, one other item these distribution lists may contain is instructions to send the email to the recipients in another named distribution list. And then, that distribution list may have instructions to send the email to the recipients in yet another distribution list. The best way to handle these nested distribution lists? You got it! Recursion.

The distribution list processing subprocedure in the emailing program is initially called with the name of the distribution list sent to the program. The subprocedure reads through the distribution list file and processes each entry. If the entry is an instruction to process another distribution list, the subprocedure recursively calls itself, passing the name of the nested distribution list. And so on and so on.

Because the subprocedure reads a file, it must save the current record pointer before the recursive call. Since files are globally defined, there is only one open data path used by all invocations of the subprocedure.

Indirect Recursion and Automatic Production Scheduling

As my company's products are constructed, phases of the construction can be either scheduled or completed. When phases are scheduled or completed, our system automatically schedules future phases of construction. For example, when Phase A is scheduled, Phase B and Phase C are scheduled automatically. Here's the thing: The scheduling of Phase B may also trigger automatic scheduling of other phases. Then, the automatic scheduling of those phases may trigger the scheduling of still other phases. The scheduling of Phase B may trigger the scheduling of Phase D, which then triggers Phase E. Meanwhile, Phase C may trigger Phase F.

Recursion again. This time, we have an indirect recursion solution. We have two programs (they really should be subprocedures, but they aren't yet). "Schedule" schedules a phase. "AutoSchedule" processes the automatic scheduling of phases triggered by the phase passed to it. You can see where this is going: To schedule Phase A, we send Phase A to "Schedule." "Schedule" schedules Phase A and then calls "AutoSchedule" to automatically schedule phases triggered by Phase A. "AutoSchedule" sees that Phase B must be scheduled. How does "AutoSchedule" do that? It calls "Schedule" recursively, sending it Phase B. And "Schedule," after scheduling Phase B, calls "AutoSchedule" to automatically schedule phases triggered by Phase B. And so on and so on. These two programs keep calling each other until all phases that should be scheduled are scheduled.

Now, it is common knowledge that, on the iSeries, programs cannot be recursive. That's mostly true: OPM programs and ILE programs within the same activation group cannot be recursive. For a program to call itself, directly or indirectly, the recursive invocation of the program must be in a different activation group. So "Schedule," "AutoSchedule," and any recursive program, are compiled with ACTGRP(*NEW). Each invocation of the program will be started in a new activation group, and recursion will be possible. Take Note: This is a big, resource hogging performance hit!

These new activation groups mean that each invocation of a program will have its own open data path to a file, unlike subprocedures.

Another Use for Recursion: Unique ID Incrementer

Browsing through the forums on Bob Cozzi's Web site one day, I came across a question from a programmer who was looking for a way to write a procedure that would increment a unique ID. This wasn't a simple numeric ID he wanted to increment. His ID was alphanumeric, containing sequences of just letters in some positions of the ID, letters and numbers in others, and just numbers in still others.

Think of a license plate in the form of xxxnnnn, with xxx being letters and nnnn being numbers. The sequence would be AAA0000, AAA0001...AAA9999, AAB0000...AAB9999, AAC0000...AAZ9999, ABA0000...ABA9999, ABB0000...AZZ9999, BAA0000 all the way to ZZZ9999. This was the type of ID the poster wanted to increment.

Well, this is another prime example of recursion at work. Here's a subprocedure that would increment our license plate:

The prototype:

D Incr            PR                  like(String)     
D   @String                           like(String)     
D   @Char                        5I 0 const            
D                                     options(*nopass)

@String is the string that is to be incremented. How you define this is up to you. For this example, String is seven characters. @Char is the character position in the string to be incremented. When it is not passed in--as in the case of the initial call--it will be the last (rightmost) character.

A call to the procedure:

String = Incr(String);

The procedure:

P Incr            B                                                      
D Incr            PI                  like(String)                       
D   @String                           like(String)                       
D   @Char                        5I 0 const                              
D                                     options(*nopass)                   
D                                                                        
D rString         S                   like(Incr)                         
                                                                         
D c               S                   like(@Char)                        
D s               S                   like(@Char)                        
D                                                                        
D Sequence        S             36A   varying inz                        
D SequenceX       S             26A   inz('ABCDEFGHIJKLMNOPQRSTUVWXYZ')  
D Sequence9       S             10A   inz('0123456789')                  
                                                                         
 /free                                                                   
1 clear rString;                                                         
                                                                         
2 if @String = 'ZZZ9999';                                                
      return 'AAA0001';                                                  
  endif;                                                                 
                                                                         
3 if %parms() <= 1;                                                      
      c = %len(@String);                                                 
  else;                                                
      c = @Char;                                       
  endif;                                               
                                                       
4 if  c >= 4;                                          
      Sequence = Sequence9;                            
  else;                                                
      Sequence = SequenceX;                            
  endif;                                               
                                                       
5 rString = @String;                                   
                                                       
6 s = %scan(%subst(@String:c:1):Sequence);             
7 if s >= %len(Sequence);                              
      %subst(rString:c:1) = %subst(Sequence:1:1);      
      return Incr(rString:c - 1);                      
  else;                                                
      %subst(rString:c:1) = %subst(Sequence:s+1:1);    
      return rString;                                  
  endif;                                               
                                                       
 /end-free                                             
                                                       
P Incr            E     
  1. rString will be the result string that is returned.
  2. Here, if the string is at the last possible value, we will return the first possible value.
  3. Here, we process the optional second parm, which indicates which string character will be incremented. On the initial call, when it is not passed in, it will be set to the last (rightmost) string character position--the length of the string.
  4. Here, we determine the sequence to be used for the string character. For our license plate, characters 1,2, and 3 are letters, and characters 4 through 7 are numbers. You can define any sequences or combination of sequences that you like to each character position.
  5. Here, we put the passed-in string into the result string.
  6. Here, we find the position of the string character within the sequence.
  7. Now things get interesting: 1) If the string character is the last character in the sequence, we set the string character to the first character in the sequence. Then, we pass the string to a recursive call of Incr. Note that this call is passing the second parm--the preceding string character position. 2) Otherwise, we set the string character to the next character in the sequence.

Recursion is a powerful programming technique that has many uses beyond factorials and Bill of Materials. With some imagination, you can find uses for recursion in your own programming.

Doug Eckersley is the iSeries programmer with a premier homebuilder in Columbus. He has been programming on the iSeries for 10 years and has been in the business for 15. He is certified by IBM. As an exchange student host father, he has kids all over the world.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: