Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Collections and Sequences

F# Arrays: Creation, Indexing, Mutation, Slicing and the Array Module

Learn F# arrays: literals, Array.init and zeroCreate, zero-based indexing, in-place mutation, slicing, 2D arrays, the Array module with sort, map, filter, and when arrays beat lists.

An array is a fixed-size, zero-based, mutable block of elements stored contiguously in memory. It is the same T[] as in C#, which makes arrays the fastest collection for indexing and the standard currency of .NET APIs. In F# you reach for arrays when you need speed, random access, in-place updates, or when you call a .NET library. This lesson shows creation, indexing, slicing, multidimensional arrays and the Array module, whose functions mirror List.

Creating arrays

Arrays are written with [| and |]:

FSHARP
let empty: int array = [||]
let numbers = [| 1; 2; 3; 4; 5 |]
let words = [| "red"; "green"; "blue" |]
let range = [| 1 .. 5 |]
let zeros = Array.zeroCreate<int> 4            // [|0; 0; 0; 0|]
let squares = Array.init 5 (fun i -> i * i)    // [|0; 1; 4; 9; 16|]
let filled = Array.create 3 "x"                // [|"x"; "x"; "x"|]

Array.zeroCreate fills with the default value of the type (0, false, null). You must tell it the element type with <int> or an annotation. Array.init builds each element from its index.

Indexing and mutation

Indexes start at 0. Read with arr[i] (F# 6 and later) or arr.[i]. Assign with <-:

FSHARP
let scores = [| 10; 20; 30 |]
printfn "%d" (scores[0])      // 10
scores[1] <- 99
printfn "%A" scores           // [|10; 99; 30|]
printfn "%d" scores.Length    // 3

An out-of-range index throws IndexOutOfRangeException. The length is fixed at creation; to grow an array you create a new one (Array.append) or use a ResizeArray.

Arrays are mutable, even though they are not declared with mutable. The binding scores cannot change to point at another array, but the contents can. Copy before changing if others hold the same array:

FSHARP
let copy = Array.copy scores
copy[0] <- -1
// scores is unaffected

Equality of arrays is structural for =, unlike in C#: [|1; 2|] = [|1; 2|] is true.

Slicing

FSHARP
let a = [| 10; 20; 30; 40; 50 |]
a[1..3]      // [|20; 30; 40|]
a[..2]       // [|10; 20; 30|]
a[3..]       // [|40; 50|]
a[^1]        // 50 (last item; ^ counts from the end, F# 6+)

Slices copy the selected items into a new array. Remember that F# slice ends are inclusive.

The Array module

Most List functions have Array counterparts with the same names and argument order, so pipelines look identical:

FSHARP
let nums = [| 5; 3; 8; 1 |]

nums |> Array.map (fun n -> n * 2)         // [|10; 6; 16; 2|]
nums |> Array.filter (fun n -> n > 2)      // [|5; 3; 8|]
nums |> Array.sort                         // [|1; 3; 5; 8|]
nums |> Array.sum                          // 17
nums |> Array.rev                          // [|1; 8; 3; 5|]
nums |> Array.exists ((=) 8)               // true
nums |> Array.fold (+) 0                   // 17
nums |> Array.tryFind (fun n -> n > 5)     // Some 8
nums |> Array.length                       // 4
nums |> Array.append [| 0 |]               // [|0; 5; 3; 8; 1|]
Array.zip [| 1; 2 |] [| "a"; "b" |]        // [|(1, "a"); (2, "b")|]

Two functions are special to arrays:

FSHARP
let data = [| 3; 1; 2 |]
Array.sortInPlace data            // mutates data -> [|1; 2; 3|]
Array.iteri (fun i x -> data[i] <- x * 10) data
Array.fill data 0 2 7             // set a range to 7

Array.sort returns a new sorted array; Array.sortInPlace changes the original. Array.Parallel.map (and friends) spreads work over CPU cores for big, CPU-heavy transformations.

Two-dimensional arrays

Use Array2D for rectangular grids and array of arrays for jagged ones:

FSHARP
let grid = Array2D.init 3 3 (fun r c -> r * 3 + c)
printfn "%d" (grid[1, 2])       // 5
grid[0, 0] <- 100
printfn "%d %d" (Array2D.length1 grid) (Array2D.length2 grid)   // 3 3

let jagged = [| [| 1 |]; [| 2; 3 |]; [| 4; 5; 6 |] |]
printfn "%d" (jagged[2][1])     // 5

Array2D indexes with a comma grid[row, col]. Loops over a grid are a good use of nested for:

FSHARP
for r in 0 .. Array2D.length1 grid - 1 do
    for c in 0 .. Array2D.length2 grid - 1 do
        printf "%d " (grid[r, c])
    printfn ""

Arrays versus lists

Array List
Mutability mutable elements immutable
Indexing O(1) O(n)
Add to front O(n) (copy) O(1)
Memory contiguous, compact linked nodes
Pattern matching works but limited (`[ a; b
.NET APIs native needs conversion

Convert freely: List.toArray, Array.toList, Seq.toArray. Pattern matching works on fixed-length arrays, too:

FSHARP
match [| 1; 2 |] with
| [||] -> "empty"
| [| x |] -> $"one: {x}"
| [| x; y |] -> $"two: {x},{y}"
| _ -> "more"

ResizeArray

When you need an array that grows, F# offers ResizeArray<'T>, an alias for .NET's List<T>:

FSHARP
let items = ResizeArray<string>()
items.Add "a"
items.Add "b"
items.Remove "a" |> ignore
printfn "%d" items.Count       // 1

Use it for local accumulation and interop, then convert to an immutable list with List.ofSeq when you are done.

C# stand-ins

These runnable samples use C# arrays, which are the same .NET type. They show in-place mutation, copying and a 2D grid.

C# C# stand-in: mutation and copying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: a 2D grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which delimiters create an array literal?

    Arrays use [| and |]; plain brackets create a list.
  2. 2. How do you assign to the second element of an array a?

    Use the <- assignment arrow on an indexed element.
  3. 3. What is true about Array.sort?

    Array.sortInPlace mutates; Array.sort returns a new array.
  4. 4. When is an array a better choice than a list?

    Arrays offer O(1) indexing and are the native .NET collection.

Summary

  • Arrays [| ... |] are fixed-size, zero-based and mutable; index with a[i], assign with a[i] <- v.
  • Create with literals, Array.init, Array.zeroCreate and ranges; slice with a[1..3] (inclusive) and a[^1].
  • The Array module mirrors List; sort returns a copy, sortInPlace mutates.
  • Array2D handles grids; ResizeArray grows.
  • Use arrays for speed and interop, lists for recursion and pattern matching.

Next: Sequences