Recursive loops

A common concept in many programming languages, an algorithm (a data-processing code) which makes reference calls to itself is described as being "recursive". Here, a recursive loop (n), contained in a parent loop (x), makes it possible to execute the loop (x) again, by automatically passing it the required arguments. Therefore, inside the loop (x), the same loop (x) is called with different parameters. This is what we refer to as recursion. This process will be repeated as many times as the recursive loop returns results.

<BOUCLEx(TABLE){id_parent}>
  ...
  <BOUCLEn(BOUCLEx) />
  ...
</BOUCLEx>

When a site has many sub-sections, or many forum messages, it often uses recursive loops. This makes it possible to display identical elements very easily.

Example

We can use a recursive loop to display a list of all of the sections in the site. To do so, we loop for the first time on the sections, with a criterion that selects the sub-sections of the current section:
{id_parent}. We also sort by numbers (assigned to the sections so that we can display them in a particular order), and then by titles (in case the numbers are absent or repeated for sections within a given parent section).

<B_rubs>
  <ul>
  <BOUCLE_rubs(RUBRIQUES){id_parent}{par num titre, titre}>
    <li>#TITRE
	<BOUCLE_sous_rubs(BOUCLE_rubs) />
    </li>
  </BOUCLE_rubs>
  </ul>
</B_rubs>

In the first iteration of the loop, {id_parent} will list the sections at the root of the site. These "root" sections all have an id_parent field equal to zero. When the first section is displayed, the recursive loop is called and so SPIP calls the loop “_rubs” again. This time the {id_parent} criterion selects a different set of sections because it will list the sub-sections of the current section. If there are sub-sections, the first one is displayed. Then the “_rubs” loop is called again, but now for this sub-section. As long as there are deeper sub-sections to display, this recursive process will repeat.

Result:

<ul>
<li>en
	<ul>
		<li>Introduction</li>
		<li>The templates
			<ul>
				<li>Loops</li>
			</ul>
		</li>
		<li>Extending SPIP
			<ul>
				<li>Introduction</li>
				<li>Pipelines</li>
				...
			</ul>
		</li>
		...
	</ul>
</li>
<li>fr
	<ul>
		<li>Introduction</li>
		<li>Template syntax
			<ul>
				<li>Loops</li>
				<li>Tags</li>
				<li>Loops criteria</li>
				...
			</ul>
		</li>
		...
	</ul>
</li>
</ul>

Understanding the principals of recursive programming is not easy. If this explanation has left you confused, you may find it helpful to read the article about recursive loops on SPIP.net:
http://www.spip.net/en_article2090.html

Author Thomas Sutton Published : Updated : 12/03/23

Translations : English, Español, français