You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$10
For Premium members:
The looping concept is introduced in programming to repeatedly execute several lines of code for specific numbers of time. In this article you will understand the looping concept in FSharp.
Introduction: The looping concept is introduced in programming to repeatedly execute several lines of code for specific numbers of time. Generally lines of code execute one-by-one, meaning one line then another line then another and so on. When we need to execute a specific line of codes repeatedly for a certain time, then we can use looping concept. Loops are also referred as repetition or iteration. Now, we try to understand looping concepts in FSharp. We start with a simple While loop. while Loop: The body of while loop is executed until given the conditional expression evaluates to false. At first, the given condition is evaluated, if the condition is true then the body of the loop is executed then again the condition is evaluated. This process continues till condition is true. Its syntax is given below while condition_exp do body of loop
Write the following code in a F# application. //while loop let mutable i=0 while i<10 do i<- i+1 printfn " %d" i
Run the application, the output will look like below: For Loop: We use a for loop when there is a need to execute several lines of code for a fixed number of times. Simple For Loop: In a simple for loop, the start and end value is specified. The body of the for loop is iterated till the counter is less than the end value. Its syntax is given below for identifier=start_value to/downto end_value do body of for loop
We write the following code. //simple for loop using to
for i=1 to 10 do printfn " %d" i
Run the application, the output will look like below:
We write the following code. //simple for loop using downto for i=10 downto 1 do printfn " %d" i
The output will look like the below figure:
For Loop With Collections: In F#, a for loop is also used with collections. It acts the same as foreach in C#. Its syntax is given below for pattern in Exp do body of loop For Loop with List: //for loop with list let simplelist=[2;4;6;8;10] for i in simplelist do printfn " %d" i The output will look like as below figure: For Loop With Array: //for loop with array let arr=[|1;2;3;4;5|] for i in arr do printfn " %d" i
The output will look like below: For Loop With Integer Range: //for loop with integer range for i in 1..5 do printfn " %d" i
The output will look like below: For Loop With character Range: //for loop with character range for i in 'a'..'e' do printfn " %c" i
Output will look like below:
Pro WPF: Windows Presentation Foundation in .NET 3.0