English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Instructions de boucle Erlang

Erlang is a functional programming language, and something that all functional programming languages need to remember is that they do not provide any loop constructs. Instead, functional programming relies on the concept of recursion.

while statement implementation

Since Erlang does not have a direct while statement, it is necessary to use the recursive technology available in Erlang to execute the implementation of the while statement.

We will try to follow the same general process as other programming languages for the implementation of the while loop. The following is the general process to be followed.

Let's look at an example of how to implement a while loop in Erlang using recursion.

Instance

-module(helloworld). 
-export([while/1, while/2, start/0]). 
while(L) -> while(L,0). 
while([], Acc) -> Acc;
while([_|T], Acc) ->
   io:fwrite("~w~n",[Acc]), 
   while(T,Acc+1). 
   
   start() -> 
   X = [1,2,3,4], 
   while(X).

Pour le programme ci-dessus, il est important de noter les points suivants-

  • Define a recursive function called while that simulates the implementation of the while loop.

  • As an example, input the list of values defined in the variable X into our while function.

  • The while function retrieves each list value and stores the intermediate value in the variable 'Acc'.

  • Then recursively call the while loop for each value in the list.

The output of the above code will be-

Sortie

0
1
2
3

for statement

Since Erlang does not have a direct for statement, it is necessary to use Erlang's recursive technology to implement the for statement.

Nous essaierons d'implémenter la boucle for de la même manière que dans d'autres langages de programmation. Voici le processus général à suivre.

Voyons un exemple d'implémentation de la boucle for en utilisant la récursion dans Erlang.

Instance

-module(helloworld). 
-export([for/2,start/0]). 
for(0,_) -> 
   []; 
   
   for(N,Term) when N > 0 -> 
   io:fwrite("Bonjour~n"), 
   [Term|for(N-1,Term)]. 
   
start() -> 
   for(5,1).

Pour le programme ci-dessus, il est important de noter les points suivants-

  • Nous définissons une fonction récursive qui simule notre implémentationBoucle for.

  • Nous avons utilisé des protections dans la fonction "for" pour assurer que la valeur de N ou la limite est positive.

  • Nous appelons récursivement la fonction for en réduisant la valeur de N à chaque appel récursif.

La sortie du code suivant sera :

Sortie

Bonjour
Bonjour
Bonjour
Bonjour
Bonjour