Imperative Control Statements in F#


Imperative Control statements

F# mainly increases the use of Functional Programming. F# contains constructs that allow you to write code in a more perfect style as well. A statement does something, has no return value, and can not be passed into a function as an argument. Conditional statements are features of a programming language that perform various computations or actions depending on whether you specified a Boolean that evaluates true or false. F# supports all imperative ways of approaching problems. F# takes a different approach than most functional programming language in that the evaluation of a statement can be put in any order. In F# we have a very succinct way of doing it with the if, elif and else statements.
If-Then/elif/else Decision

If-Then statements are common in many programming language although the syntax is different a little bit from language to language. The F# syntax looks like below:
Syntax-

// Syntax of If/than/elif/else
(* simple if *)
if expr then
    expr
(* binary if *)
if expr  then
    expr
else
    expr
(* multiple else branches *)
if expr then
    expr
elif expr then
    expr
elif expr then
    expr
...
else
    expr

Or

if a then
b
else c

First a is evaluated then if and only if a evaluates to true than it executes b otherwise it evaluates c.

If you consider a, b, c as statements then you can say that executes statement1 if the expression result is logically true. The else clause of if statements is optional. If the expression result is logically False and an else statement exists then the statements associated with the else statement will execute. When multiple if statements exists and the else clause is present, the else is related with the nearest preceding if statement in the same block.

Example-

If-else Example

open System
let printMessage condition =
    if 5<6 then
        printfn "6"
        else
    printfn
"5"
let main() =
    printMessage true
    printfn "******"
    printMessage false
    Console.ReadKey(true) |> ignore
main()

Output-

If-Else

Work with conditions
 

Symbol Description Example
|| Logical OR (True || False) returns True
&& Logical AND (True && False) returns False
Not Logical Not (Not False) returns True

For Loop

The standard for a loop is to start at a particular index value, check for the terminate condition and then increment or decrement the index. F# supports looping constructs in standard way. By default the increment is 1. In F# the body of the for Loop will be unit type. A for loop is categorized as an iteration statement. A loop is a sequence of statements which are specified once but may be executed several times in succession. The code inside the loop is  executed a specified number of times. Traditionally this is used to iterate over a well defined integer range.
Example-
For Loop 1

let main() =
    for n = 2 to 20 do
        printfn "n: %i" n
main()

Output-
For Loop1

Example-
Computing an average with the help of a for loop.

For Loop2

open System
let main() =
    Console.WriteLine("A program which takes input from user to compute Average.")
    printfn "****************************************"
    Console.Write("Enter how many number's average you want to compute? ")
    let mutable sum = 0
    let numbersToAdd = Console.ReadLine() |> int
    for n = 1 to numbersToAdd do
        Console.Write("Enter number{0}: ", n)
        let input = Console.ReadLine() |> int
        sum <- sum + input
     let average = sum / numbersToAdd
    Console.WriteLine("The Computed Average is : {0}", average)
main()

Output-
For Loop2

While Loop

F# also supports a while construct. A while loop will repeat a block of code indefinitely while a particular condition is true. A while loop is the same as the Imperative construct. A while loop is of Unit Type so this does not return a value.

Syntax-

while expr do
 ...
// Body of Loop

Example-
While Loop

let a= ref 6
while !a>4 do
printfn "a=%d\n" !a
a:=!a-1

Output-
While Loop

Summary-

In this article I have covered Imperative Control Statements of F#.

Up Next
    Ebook Download
    View all
    Learn
    View all