Javatpoint Logo
Javatpoint Logo

F# Arrays

Arrays are mutable collection of data of same type. It starts from 0 index and goes to n-1. Here, n is length of arrays. F# arrays support all the functionality available in System.Array of .Net Framework.

F# array

F# Arrays Types

F# provides mainly 2 types of Arrays

  1. Single dimensional arrays
  2. Multidimensional arrays

F# Single Dimensional Array

You can create an array by adding values between [| and |] separated by semicolon (;).

You can also create an array by using sequence of expressions. The following example creates an array of integer having values from 1 to 10.


F# Built-in methods to create arrays

There are various built-in methods in System.Array. It helps to create arrays according to requirement. You can use these methods to create arrays in F#.

Method Description
Array.empty Ex. let arr = Array.empty It creates a new array which does not contain element.
Array.create Ex. let arr = Array.create 10 2 It creates an array of a specified size and sets all the elements to provided value.
Array.init Ex. let arr = Array.init 10 (fun index -> index) It creates an array by using given dimension and a function to generate the elements.
Array.zeroCreate Ex. let arr = Array.zeroCreate 10 It creates an array in which all the elements are initialized to zero.

F# Single Dimensional Arrays Example

Output:

1
2
3
4
5


F# Single Dimensional Array Using Sequence of Expression

Output:

1
2
3
4
5
6
7
8
9
10

F# Create an Arrays by using Array.create method and Traverse by using For-In Loop

F# Array.create method creates an arrays of specified length and set the entire array by specified value. You can latter assign or set new value by using Array.set method followed by index and value.

Output:

0
12
0
0
0

F# Passing Array to function: print array elements

Output:

Printing array elements:
25
10
20
15
40
50
Printing array elements:
12
23
44
11
54

F# Passing array to function: print minimum number

Output:

Minimun element is: 10
Minimun element is: 11

F# Passing Array to function: print maximum number

Output:

Maximum element is: 50
Maximum element is: 54

F# Multidimensional Arrays

F# allows us to create multidimensional array. Multidimensional array also known as array of array. It can be 2 dimensional, 3 dimensional or more.

In F#, multidimensional array can be created, but there is no syntax for writing a multidimensional array. F# use array2D operator to create two dimensional array from sequence of sequences of array elements. The sequences can be array or list.


F# Multidimensional arrays

Here, we are using array2D operator to create a 2D array.

Output:

1 0
0 1

F# print array matrix without using loop

You can print array matrix by using %A (a format specifier ) in printf function.

Output:

[[1; 0]
 [0; 1]]
Next TopicF# Sequence




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA