Fsharp: array

By Xah Lee. Date: . Last updated: .
xtodo

ai answer

3. Arrays

An array ('T[]) is a mutable, fixed-size, contiguous collection. It has excellent random-access performance.

Creating Arrays

// Array literal
let arr = [| 1; 2; 3; 4; 5 |]

// Range
let rangeArr = [| 1..10 |]

// Array comprehension
let cubes = [| for i in 1..5 -> i * i * i |]

// Empty array
let emptyArr: int[] = [||]

Accessing and Mutating

printfn "First element: %d" arr.[0]
arr.[0] <- 99          // Mutation (arrays are mutable)

// Slicing
let slice = arr.[1..3]   // [|2; 3; 4|]  (new array)

Common Operations

let doubledArr = Array.map (fun x -> x * 2) arr
let sumArr     = Array.sum arr

// In-place mutation
Array.sortInPlace arr

// Convert between collections
let listFromArr = Array.toList arr
let arrFromList = List.toArray [1; 2; 3]

Performance Comparison

Operation List Array
Random access O(n) O(1)
Prepend (cons) O(1) O(n)
Append O(n) O(n)
Memory overhead Higher (links) Lower (contiguous)
Mutability Immutable Mutable

Working Together

// Tuple containing list and array
let data = ([1; 2; 3], [|4; 5; 6|])

// Function returning tuple of results
let stats (nums: int list) =
    let arr = List.toArray nums
    (List.sum nums, Array.averageBy float arr, List.length nums)

// Using all three
let processData () =
    let lst = [1..5]
    let arr = lst |> List.toArray
    let sum, avg, len = stats lst
    (sum, avg, len, arr)

Summary Table

Feature Tuple List ('T list) Array ('T[])
Size Fixed Variable Fixed
Mutability Immutable Immutable Mutable
Access time O(1) O(n) for indexing O(1)
Memory layout Contiguous Linked nodes Contiguous
Best for Small fixed groups Functional pipelines Performance-critical
Typical module Built-in List Array

Next Steps

Would you like me to expand any section with more examples (recursion, performance benchmarks, JSON serialization, etc.)?

Reference

fsharp data structure