Array Examples
This page was last reviewed on Dec 22, 2023.
Dot Net Perls
Array. In F# we can store elements (like strings and ints) in an array. This is a low-level, efficient type. Elements are stored in a linear way.
byte Array
Shows an array
Array notes. An array stores its elements together in memory. It has no head or tail, but we can quickly loop over the elements within an array.
First example. This example creates an array from a range of numbers (enclosed in vertical bars). The array has 4 elements. The Length property returns 4.
Note The first element in an array is at index 0. We use a period before the index brackets.
Note 2 The last element in a nonempty array is equal to the length minus 1. We sometimes need to check for an empty array.
Shows an array
// Create an array of 4 ints. let array = [|0 .. 3|] printfn "%A" array // Access the Length property. let length = array.Length printfn "Length = %A" length // Access the first and last elements with indexes. let first = array.[0] printfn "First = %A" first let last = array.[array.Length - 1] printfn "Last = %A" last
[|0; 1; 2; 3|] Length = 4 First = 0 Last = 3
Create, for. Arrays can be used in many ways. We call Array.create to construct an array of 4 elements, all with the string "empty." We then use a for-loop over each index in the array.
Tip We assign elements in the array with an index. We must use the left-pointer operator.
Finally Printfn() inserts a newline at the end. It prints all an array's elements. No looping is needed.
// Create an array of 4 strings with the string empty. let sizes = Array.create 4 "empty" // Assign all values to full. for i = 0 to sizes.Length - 1 do sizes.[i] <- "full" // Assign first value to special string. sizes.[0] <- "start" // Display result. printfn "%A" sizes
[|"start"; "full"; "full"; "full"|]
All elements. Here we create a string array with 3 strings in it. We specify all elements in the initialization statement. No range syntax is needed.
// Create an array with all elements specified. let values = [|"cat"; "bird"; "fish"|] // Loop over elements and display them. for v in values do printfn "%A" v
"cat" "bird" "fish"
Find elements. We can find elements in an array with Array.tryFind and tryFindIndex. These functions do not throw exceptions, so they are safer than find and findIndex.
Start We pass a lambda that returns true if the value is equal to or greater than 9. We use IsSome on the optional int returned.
Note IsSome() tests the optional int (similar to a Nullable in C#) for a valid internal value. We access that value.
Next We locate the index where an element is equal to 15. In our array, this is located at index 2 (the third element).
Finally We use Array.get with two arguments: the array and the index of the element we want to get. This returns the element value.
let values = [|5; 10; 15|] // Find an element greater than or equal to 9. let result = Array.tryFind (fun x -> x >= 9) values // See if option has a value. if result.IsSome then do printfn "Greater or equal to 9: %A" result.Value // Find index where value is 15. let resultIndex = Array.tryFindIndex (fun x -> x = 15) values // See if option has a value. if resultIndex.IsSome then do // Print value and get the element. printfn "Index with value equal to 15: %A" resultIndex.Value printfn "%A" (Array.get values resultIndex.Value)
Greater or equal to 9: 10 Index with value equal to 15: 2 15
Get elements. With Array.get we get an element at an index from an array. We pass two arguments to Array.get: the array name, and the element index.
Tip We can read F# function calls as sentences. Here "Array.get volumes 2" is like an English command.
let volumes = [|20 .. 30|] // Get second element from the array (at index 1). let elementTwo = Array.get volumes 1 printfn "Element two: %A" elementTwo // Get third element from the array (at index 2). printfn "Element three: %A" (Array.get volumes 2)
Element two: 21 Element three: 22
Array.append. We combine two arrays with Array.append. This function takes two arguments: the first array and the second. It returns those arrays combined together.
let array1 = [|10; 20; 30|] let array2 = [|40; 50; 60|] // Append the second array to the first. let merged = Array.append array1 array2 // Print lengths of the arrays. printfn "%d + %d = %d" array1.Length array2.Length merged.Length // Print the merged array. printfn "%A" merged
3 + 3 = 6 [|10; 20; 30; 40; 50; 60|]
AllPairs. F# has the ability to do solve puzzles and analyze complex data. Here we use allPairs. This takes 2 arrays, and returns all possible pairs of elements of the 2 arrays.
So It takes each element from the first array, and creates a pair with each element from the second array.
Tip If you need algorithm that handles all possible pairings from 2 arrays, use allPairs.
let array1 = [|1; 2; 3|] let array2 = [|1; 2; 3|] // Use allPairs to get all possible pairs from 2 arrays. let pairs = Array.allPairs array1 array2 printfn "%A" pairs
[|(1, 1); (1, 2); (1, 3); (2, 1); (2, 2); (2, 3); (3, 1); (3, 2); (3, 3)|]
Seq.ofArray. An array does not have functions like map on it. Instead, we can use it as a sequence by calling Seq.ofArray. We can then use Seq.toArray to convert back to an array if needed.
Summary. Arrays are a fundamental data type. They are everywhere—and even in a functional, high-level language like F# they are critical. They store data in an efficient way.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (edit link).
© 2007-2024 Sam Allen.