TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to F#

F# Array Examples

Instantiate arrays of strings and ints. Use ranges, accesses elements and stores values in arrays.
Arrays. In the park we find an array of animals: a cat, a dog, a bird. In F# we can store elements (like strings) in an array. This is a low-level, efficient type.
With list, a special F# type, we have a linked list. But an array stores its elements together in memory. It has no head or tail, but we can quickly loop over it.
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.

First: The first element in an array is at index 0. We use a period before the index brackets.

Last: The last element in a nonempty array is equal to the length minus 1. We sometimes need to check for an empty array.

F# program that uses 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 Output [|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.

Assign: We assign elements in the array with an index. We must use the left-pointer operator.

Printfn: This call inserts a newline at the end. It prints all an array's elements. No looping is needed.

Printfn
F# program that uses Array.create, loop // 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 Output [|"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.
F# program that specifies all elements // 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 Output "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.

TryFind: 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.

IsSome: This tests the optional int (similar to a Nullable in C#) for a valid internal value. We access that value.

TryFindIndex: Here we locate the index where an element is equal to 15. In our array, this is located at index 2 (the third element).

Get: We use Array.get with two arguments: the array and the index of the element we want to get. This returns the element value.

F# program that uses Array.tryFind 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) Output 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.

F# program that uses Array.get, gets elements 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) Output 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.
F# program that uses append 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 Output 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.

F# program that uses 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 Output [|(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.Convert: Seq.ofArray
A summary. Arrays are a fundamental data type. They are everywhere. Even in a functional, high-level language like F# they are critical. They store data in an efficient way.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf