Fsharp: list

By Xah Lee. Date: . Last updated: .

ai answer

xtodo

2. Lists

An F# list ('T list) is an immutable, singly-linked list. It is the default collection for functional programming in F#.

Creating Lists

// Empty list
let empty = []
printfn "%A" empty
// []
// Literal syntax
let xx = [1; 2; 3; 4; 5]
printfn "%A" xx
// [1; 2; 3; 4; 5]
// Range syntax
let xrange = [1..10]
printfn "%A" xrange
// [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
let xeven = [2..2..10]
printfn "%A" xeven
// [2; 4; 6; 8; 10]
// List comprehension
let xsquares = [ for i in 1..5 -> i * i ]
printfn "%A" xsquares
// [1; 4; 9; 16; 25]

Prepending (most efficient operation)

let newList = 0 :: numbers          // [0; 1; 2; 3; 4; 5]
let combined = [0..2] @ numbers     // Concatenation with @

Accessing Elements

match numbers with
| head :: tail -> printfn "Head: %d, Tail: %A" head tail
| [] -> printfn "Empty"

printfn "First element: %d" numbers.Head
printfn "Rest: %A" numbers.Tail

Common Higher-Order Functions

let doubled = List.map (fun x -> x * 2) numbers          // [2; 4; 6; 8; 10]
let evens   = List.filter (fun x -> x % 2 = 0) numbers   // [2; 4]
let sum     = List.sum numbers                            // 15
let product = List.reduce (*) numbers                     // 120

Pattern Matching on Lists

let rec sumList lst =
    match lst with
    | [] -> 0
    | head :: tail -> head + sumList tail

When to use Lists:

Reference

fsharp data structure