F# Mutable Lists

In this article, our goal is to help you understand how to create, modify, and iterate over F# Mutable Lists. You will learn how to work with lists functionally, regardless of your experience level with F#.

Whether you are a beginner or an experienced developer, this guide will provide valuable insights on creating, modifying, and iterating over these lists.

Functional programming adheres to the fundamental principle of using immutable data structures, but there are times when mutable data structures are more appropriate.

One such instance is when an algorithm needs to modify a list in-place, which is a common procedure in many algorithms.

For this purpose, the List <T> class is often used as it defines a strongly typed list of objects that can be accessed by index.

However, mutable counterparts of the List class are also available. Much like arrays, lists provide a way of accessing a collection of items through an index.

However, unlike arrays, lists are resizable, and the size of the object does not need to be specified during the declaration process.



Creating F# Mutable Lists

The simplest form of creating F# Mutable Lists is by using the new keyword and calling the constructor of the list.

This can be demonstrated through the following example:

Example: 

open System.Collections.Genericlet fruits = new List<string>() fruits.Add("Banana") fruits.Add("Watermelon") fruits.Add("Pear") fruits.Add("Apple") fruits.Add("Mango") fruits.Add("Pineapple")fruits |> Seq.iteri (fun index item -> printfn "%i: %s" index fruits.[index])

And the result will be:

0: Banana
1: Watermelon
2: Pear
3: Apple
4: Mango
5: Pineapple

F# List(T) Class

This List(T) class behaves as a strongly typed list of objects whose indexes can be accessed to retrieve the objects within it.

A list can be searched, sorted, and manipulated using methods provided by the program.

Below you will find the properties, constructors, and methods of the List(T) class, listed in the following tables:

PropertiesOverview
CapacityThis method can be used to determine the total number of elements the internal data structure is capable of holding without having to resize it.
CountIt returns how many elements are contained in the List(T).
ItemIt is used to get or set an element at an index specified by an index value.

ConstructorsOverview
List(T)()Initially, this function creates an empty instance of the List(T) class with the default initial capacity of 1 and an empty list item.
List(T)(IEnumerable(T))The list() constructor creates a new instance of the List(T) class in which the elements copied from the specified collection are inserted into the new instance. This new instance has sufficient capacity to accommodate the number of elements copied from the collection.
List(T)(Int32)The List(T) class is used to create new instances of the empty List(T) class that have the initial capacity specified and begin with an empty list.

MethodsOverview
AddA new object is added to the end of the List(T).
AddRangeA list of elements from a specified collection will be added to the end of the List(T).
AsReadOnlyThis method returns an IList(T) wrapper that is read-only for the current collection.
BinarySearch(T)Uses the default comparer to search a sorted List(T) for an element, and returns one based on the zero-based index of that element within the sorted List(T).
BinarySearch(T, IComparer(T))It involves searching the entire sorted List(T), using the specified comparer, for an element based on its zero-based index, and returning that element’s index.
BinarySearch(Int32, Int32, T, IComparer(T))Using the specified comparer, searches for an element in a range of elements in the sorted List(T) and returns the number of the element’s zero-based index as a result of the search.
ClearA method for removing every element from a List(T).
ContainsThis function determines whether or not an element belongs to the List(T).
ConvertAll(TOutput)The list will be converted to another type, and this result will be a list containing the elements that have been converted.
CopyTo(T[])The function copies every element of List(T) into a compatible one-dimensional array, starting from the very beginning of the target array.
CopyTo(T[], Int32)Assigns the whole List(T) to the specified index in a one-dimensional array that is compatible with the List(T), starting at the specified index in the target array.
CopyTo(Int32, T[], Int32, Int32)There is one method that copies elements from List(T) to a compatible one-dimensional array, starting at the specified index in the target array, by copying an array element at a time.
Equals(Object)In this method, we determine whether the specified object matches the current object or not. (Inherited from the object.)
ExistsList(T) is checked to see if the elements in the List(T) satisfy the conditions set out by the predicate defined in the test.
FinalizeThe ability to perform other cleanup operations, such as freeing up resources, before an object is reclaimed by garbage collection, is available (inherited from Object).
FindThis method searches for elements that meet the conditions specified in the specified predicate, and returns the first element found within the entire collection of elements contained in List(T).
FindAllUsing the predicate specified in the request, this function will return all the elements that meet the criteria defined in the request.
FindIndex(Predicate(T))A search function that searches within the entire list of elements for those that match the specified predicate in order to return the zero-based index of the first instance of the element within the entire List(T).
FindIndex(Int32, Predicate(T))There is a predicate in the List() function that is used to search for elements that match the conditions described by the predicate. The result is the zero-based index that represents the first occurrence of the element that matches the specified predicate within the range of elements in the List(T).
FindIndex(Int32, Int32, Predicate(T))As the predicate specifies, the element should be searched for that matches the conditions specified by the predicate, and the order in which it appears in the List(T) shall be determined by the zero-based index allocated to the first occurrence within the range of elements in the List(T) that starts at that index and contains the elements in that range.
FindLastThere is a predicate that specifies the conditions that need to be met in order to return an element that matches those conditions. In this case, it returns the last occurrence found in the entire List(T).
FindLastIndex(Predicate(T))The Predicate search function uses the given predicate to seek out elements that match the conditions set out by the predicate, and it will return the zero-based index of the last occurrence among all elements of the List(T).
FindLastIndex(Int32, Predicate(T))There will be some elements within List(T) that meet the predicats specified by the predicate, and it will return the zero-based index of the last occurrence for each of the elements within the range that extends from the first element to the specified index on the List(T).
FindLastIndex(Int32, Int32, Predicate(T))List(T) will contain some elements that satisfy the predicates specified in the predicate, and for each element within the range starting from the first element to the specified index on List(T), the module will return the zero-based occurrence index of the last instance for each element within the range that extends from the first element to the specified index on List(T).
ForEachSpecifies the action that should be performed on each element of the List(T).
GetEnumeratorThis function returns an enumerator that is able to iterate over the List(T).
GetHashCodeThis function is used as the default hash function. (Inherited from the Object.)
GetRangeCreating a shallow copy of an element range that is contained in a source List(T).
GetTypeThe current instance’s type is returned by this method. (Inherited from an object.)
IndexOf(T)A zero-based index is returned to indicate where the first occurrence of the specified object appears in the entire List(T).
IndexOf(T, Int32)Using this method, you can search and return the zero-based index of the first occurrence of the specified object within the range of elements in the List(T), starting from the specified index and ending with the last element.
IndexOf(T, Int32, Int32)This function performs a search for a specified object and returns the zero-based index of the first occurrence within the range of the elements in the List(T) that contains the specified number of elements starting at that specified index and that start at the specified index.
InsertThis function inserts an element at the given index into the List(T).
InsertRangeList(T) is used to insert elements of a collection at a specified index into the collection.
LastIndexOf(T)Finds the object specified by the object parameter and returns the zero-based index that indicates where the object last occurred within the entire List(T).
LastIndexOf(T, Int32)This function searches for the specified object and returns the zero-based index of its last occurrence from the first element of the List(T) to the specified index within the range of elements in the List(T).
LastIndexOf(T, Int32, Int32)Returns a zero-based index of the last occurrence within a Range(T) consisting of the specified number of elements and ending at the specified index within a Range(T) containing the specified number of elements within the range of elements.
MemberwiseCloneThis method will create a shallow copy of the current Object. (Inherited from the object.)
RemoveThis function will remove the first instance of a specific object from the List(T).
RemoveAllA predicate that matches the conditions of the specified element is removed from the list.
RemoveAtA method that removes the element at the specified index from a List(T).
RemoveRangeThere is an option to remove a range of elements from a List(T).
Reverse()The reverse method reverses the order of the elements in the entire List(T).
Reverse(Int32, Int32)This function reverses the order of elements within the range specified.
Sort()A sorting operation is performed on all elements in a List(T) using the default comparator.
Sort(Comparison(T))It is a method that sorts all the elements of a List(T) using the specified System. Performing a comparison (T).
Sort(IComparer(T))By using the specified comparer, this method sorts all elements in the entire List(T) in the specified order.
Sort(Int32, Int32, IComparer(T))By using the specified comparer, the elements in List(T) are sorted based on the range of elements in the list.
ToArrayArray() creates a new array from the elements of the List(T) by copying them to it.
ToStringThe function returns a string containing the name of the current object. (Inherited from an object.)
TrimExcessUpon calling the function, the current object’s name will be returned as an object string. A class that inherits from an object.
TrueForAllThe purpose of this function is to determine whether all elements in the List(T) satisfy the conditions identified by the predicate specified.

Example: 

// Creating a List open System.Collections.Genericlet fruits = new List<string>() fruits.Add("Banana") fruits.Add("Watermelon") fruits.Add("Pear") fruits.Add("Apple") fruits.Add("Mango") fruits.Add("Pineapple")printfn"Total %d fruits" fruits.Count fruits |> Seq.iteri (fun index item -> printfn "%i: %s" index fruits.[index]) fruits.Insert(1, "Roots")printfn("\nAfter inserting at index 1") printfn"Total %d Fruit list will be" fruits.Countfruits |> Seq.iteri (fun index item -> printfn "%i: %s" index fruits.[index]) fruits.RemoveAt(2)printfn("\nAfter removing from index 2") printfn"Total %d Fruits" fruits.Countfruits |> Seq.iteri (fun index item -> printfn "%i: %s" index fruits.[index])

And the output will be as follows:

Total 6 fruits
0: Banana
1: Watermelon
2: Pear
3: Apple
4: Mango
5: Pineapple

After inserting at index 1
Total 7 Fruit list will be
0: Banana
1: Roots
2: Watermelon
3: Pear
4: Apple
5: Mango
6: Pineapple

After removing from index 2
Total 6 Fruits
0: Banana
1: Roots
2: Pear
3: Apple
4: Mango
5: Pineapple

Example Explanation

  • You can see above example of using F# programming language to create a list of fruits. To do this, the List <T> class from the System.Collections.Generic namespace is used. This class allows you to store elements of any data type in a collection, in this case, the data type used is a string.
  • Once the list is created, the Add method of the List <T> class is used to add six fruits to the list. The Count property is then used to get the number of elements in the list, which is printed using printfn.
  • Next, the Seq.iteri function is used to iterate over the list and print each element with its index. This function takes a function as an argument and applies it to each element in the sequence. In this case, the function takes two arguments: index and item, where index is the index of the current item and item is the current item itself.
  • After that, the code uses the Insert method of the List <T> class to insert the string “Roots” at index 1 in the list. The Count property is used again to print the number of elements in the list, and the Seq.iteri function is used again to print the updated list.
  • The RemoveAt method of the List <T> class is then used to remove the element at index 2 from the list. The Count property is used once more to print the number of elements in the list, and the Seq.iteri function is used for the third time to print the updated list.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *