English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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 implementation process as other programming languages for the while loop. The following is the general process to follow.
Let's look at an example of how to implement a while loop using recursion in Erlang.
-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).
The following points should be noted about the above program-
Define a recursive function called while that simulates the implementation of the while loop.
As an example, input the value list defined in variable X to 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-
0 1 2 3
Since Erlang does not have a direct for statement, it is necessary to use Erlang's recursive technology to implement the for statement.
We will try to implement the for loop in the same way as followed by other programming languages. The following is the general process to be followed.
Let's look at an example of implementing the for loop recursively in Erlang as in other programming languages. The following is the general process to follow.
-module(helloworld). -export([for/2,start/0]). for(0,_) -> []; for(N,Term) when N > 0 -> io:fwrite("Hello~n"), [Term|for(N-1,Term)]. start() -> for(5,1).
The following points should be noted about the above program-
We are defining a recursive function that will simulate our implementationFor loop.
We use protection measures in the 'for' function to ensure that the value or limit of N is positive.
We call the for function recursively by reducing the value of N in each recursive call.
The output of the above code will be:
Hello Hello Hello Hello Hello