F# Lists
List is a immutable collection of same type elements. It does not allow duplicate elements. It maintains order of elements.
F# Creating and initializing list Example
There are various ways to create list. Some are describing below.
F# List Example
Output:
1 2 3 4 5 6 7 8 9
F# Add new element to list Example
You can add new element into list by using :: (cons) operator. Let’s see an Example.
Output:
1 2 3 4 5 0 1 2 3 4 5
F# Concatenation of Two List Example
You can concatenate two lists having same type by using @ operator. Let’s see an example.
Output:
1 2 3 4 5 6 7 8 9 10
F# List properties
F# list provides important properties. It helps to optimize and maintain code too.
Property | Description |
---|---|
Head | It returns first element of list. |
Empty | It returns empty list. |
IsEmpty | It returns true if list is empty |
Length | It returns number of elements. |
Tail | It returns list excluding first element. |
F# List Property Example
Ouptut:
Is list Empty: false Length of list is 5 Head element of list is 1 Tail element of Head in the list is 2 Tail element of tail of head of list 3 Element at 1 index is 2
In F#, list provides built-in functions to sort and search elements.
F# List Sort Example
Ouptut:
0 7 10 12 23 43 54 89 90
F# List Search Example
List provides List.find () function to find element in the list. It returns the first matched element and if element not found it throws System.Collections.Generic.KeyNotFoundException Exception.
Ouptut:
10
F# Zip and Unzip functions in List
Zip function combines two lists of single values into one list of tuples. Unzip function separates one list of tuples into two lists of single values.
F# List Zip Example
Output:
Given Lists: List1: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] List2: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] Result(Zipped List): [(1, 1); (2, 2); (3, 3); (4, 4); (5, 5); (6, 6); (7, 7); (8, 8); (9, 9); (10, 10)]
F# List Unzip Example
Output:
First List: [1; 3; 5] Second List: [2; 4; 6]