10.2.3 Working with arrays
An array is similar to a simple computer memory model, essentially a numbered box that can easily be read or changed in any box, as long as the number is known. Arrays form contiguous blocks of memory, so the overhead is very small and can be used to store large datasets; the array [intergenerational] is pre-allocated: Once created, the size is fixed, so the new value cannot be added to the existing array.
Arrays are mutable data structures, so it is easy to modify them. This is useful in some cases, but for functional programmers, there is a lot of protection out there about the state of the program. Let's look at the syntax of the basic F # array first, as shown in Listing 10.11.
Listing 10.11 Creating and using Arrays (F # Interactive)
> Let arr = [| 1.. 5 |];; [1]
Val arr:int array = [| 2; 3; 4; 5|]
> arr.[2] <-30;; [2]
Val it:unit = ()
> arr;
Val it:int array = [| 2; 30; 4; 5|]
> let mutable sum = 0 |
Fori in 0.. Arr. Length–1 do | [3]
sum<-arr.[i] + sum;; |
Val mutable sum:int = 42
Arrays in F # support all the basic operations we expect arrays to do. Here, we first initialize arr, using the syntax very similar to the initialization of the list [1]; Next, use the assignment operator to change the array and set the value at the specified index [2]. Note that when you access an element in F #, you must write a dot (.) before the brackets in the specified index, and in the next few lines, manipulate the array [3] in an imperative style, using a for loop to iterate through all the elements, and a mutable value to hold the sum.
If you think listing 10.11 is a bit messy, don't worry, it means you're used to the functional style. We don't usually write code like this, just to demonstrate the syntax.
Although arrays are often used for imperative programming, they can be used in a functional style. In addition to the basic operations we've seen, F # provides several higher-order functions like processing lists. Having seen the use of these functions to manipulate arrays will not feel any confusion.
10.2.3 Working with arrays