Fsharp: list

By Xah Lee. Date: . Last updated: .

ai answer

xtodo

Lists

Fsharp list is a stack data structure. You can only add one item to the front, at a time, or, remove one item in the front. You cannot change or modify anything else. In computer engineering, it is so-called linked-list.

Creating Lists

// empty list
let xx = []
printfn "%A" xx
// []
// literal syntax for list
let xx = [1; 2; 3; 4; 5]
printfn "%A" xx
// [1; 2; 3; 4; 5]
// Range syntax
let xrange = [1..9]
printfn "%A" xrange
// [1; 2; 3; 4; 5; 6; 7; 8; 9; 9]
let xeven = [0..2..9]
printfn "%A" xeven
// [0; 2; 4; 6; 8]
// List expression, aka list comprehension
let xx = [ for i in 1..5 -> i + 1 ]
printfn "%A" xx
// [2; 3; 4; 5; 6]

Prepend item

let xx = [1; 2; 3]
let xaa = 0 :: [1; 2; 3]
printfn "%A" xaa
// [0; 1; 2; 3]

join lists

let xx = [1; 2; 3]
let xbb = xx @ [4; 5]
printfn "%A" xbb
// [1; 2; 3; 4; 5]

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; 9]
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