SIGN UP MEMBER LOGIN:    
ARTICLE

Working With Array in F#

Posted by Alok Pandey Articles | F# October 05, 2011
An Array is mutable collection type in F#. Let's learn how to work with an array and its operation in F#.
Reader Level:

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#

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Nevron Gauge for SharePoint
Become a Sponsor