Working With Array in F#


Introduction: An Array is mutable collection type in F#. The element of array are defined inside square bracket with vertical bar after opening bracket and before closing bracket and array element is separate by semicolon.

Defining Array:
                       

let
array_name = [|element1;element2;element3|;.....elementn

Like, 
let array1 =[|1;2;3;4;5|]

We can also declare array using
sequence expressions. Like below code

let array1 =[|for i in 1 .. 5 ->  i|]


Accesing Array Element

An Array element is retrieved by a square bracket with the dot(.) operator. The index of the desired element is written inside the square bracket. We write the following code:

let array1 =[|1;2;3;4;5|] 

printfn "%i" array1.[0]
printfn "%i" array1.[1]
printfn "%i" array1.[2]
printfn "%i" array1.[3]
printfn "%i" array1.[4]


We run this code by pressing the  Ctrl+F5 key. The output will look like below:

 array in F#

Now we write following code for accessing array elements:

let
array1 =[|"aaa";"bbb";"ccc";"ddd";"eee"|]
printfn "%A" array1

Now, The output will look like below:
 
array in F#

Assigning an Array Element

An Array element is assigned to a array with the <- operator. Like below:

 array1.[0] <- "aaa";
 array1.[1] <- "bbb";
 array1.[2] <- "ccc";

Array Slicing

There is a special symbol for taking slice of an array. We specify the upper and lower bound for accessing a subset of an array element. Like the following code:

let array1 =[|"aaa";"bbb";"ccc";"ddd";"eee"|]
printfn "%A" array1.[2..3]

When we run this code, the output will be below:

array in F#


Similar Articles