Arrays in F#

Our first example demonstrates the use of arrays in F#. In F#, an array is a fixed-size, zero-based, mutable collection of elements of the same type.

open System

// Here we create an array `a` that will hold exactly 5 integers.
// By default, an array is initialized with default values, which for integers means 0s.
let a = Array.zeroCreate<int> 5
printfn "emp: %A" a

// We can set a value at an index using the array.[index] <- value syntax,
// and get a value with array.[index]
a.[4] <- 100
printfn "set: %A" a
printfn "get: %d" a.[4]

// The Array.length function returns the length of an array.
printfn "len: %d" (Array.length a)

// Use this syntax to declare and initialize an array in one line.
let b = [|1; 2; 3; 4; 5|]
printfn "dcl: %A" b

// F# doesn't have a direct equivalent to Go's `...` syntax for array initialization.
// However, you can use the Array.init function to achieve a similar result.
let c = Array.init 5 (fun i -> i + 1)
printfn "init: %A" c

// F# doesn't have a direct equivalent to Go's index-based initialization.
// However, you can create an array and then set specific indices.
let d = Array.zeroCreate<int> 5
d.[0] <- 100
d.[3] <- 400
d.[4] <- 500
printfn "idx: %A" d

// Array types are one-dimensional, but you can create multi-dimensional arrays.
let twoD = Array2D.zeroCreate<int> 2 3
for i in 0..1 do
    for j in 0..2 do
        twoD.[i, j] <- i + j
printfn "2d: %A" twoD

// You can create and initialize multi-dimensional arrays at once too.
let twoD2 = array2D [[1; 2; 3]; [1; 2; 3]]
printfn "2d: %A" twoD2

When you run this program, you should see output similar to this:

emp: [|0; 0; 0; 0; 0|]
set: [|0; 0; 0; 0; 100|]
get: 100
len: 5
dcl: [|1; 2; 3; 4; 5|]
init: [|1; 2; 3; 4; 5|]
idx: [|100; 0; 0; 400; 500|]
2d: [|[|0; 1; 2|]; [|1; 2; 3|]|]
2d: [|[|1; 2; 3|]; [|1; 2; 3|]|]

Note that arrays in F# are displayed in the form [|v1; v2; v3; ...|] when printed.

F# arrays are similar to those in other languages, but with some key differences:

  1. F# uses [| |] syntax for array literals instead of { }.
  2. Array indices are accessed using . notation (e.g., array.[index]) instead of [].
  3. F# doesn’t have a built-in way to create arrays with “holes” like Go’s [...]int{1, 3: 4} syntax.
  4. Multi-dimensional arrays in F# use , to separate dimensions (e.g., array2D.[i, j]).

F# also provides many useful functions for working with arrays in the Array module, which can make array manipulation more concise and functional.