FSharpx.Collections


PersistentVector

A Vector is a collection of values indexed by contiguous integers. Vectors support access to items by index in log32N hops. count is O(1). conj puts the item at the end of the vector. More details can be found in the API docs.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
open FSharpx.Collections

// Create a new PersistentVector and add some items to it
let v = 
    PersistentVector.empty 
    |> PersistentVector.conj "hello"
    |> PersistentVector.conj "world"
    |> PersistentVector.conj "!"

val v : FSharpx.Collections.PersistentVector<string>

// lookup some items
PersistentVector.nth 0 v
val it : string = "hello"
PersistentVector.nth 1 v
val it : string = "world"
v.[2]
val it : string = "!"

// Check no. of elements in the PersistentVector
PersistentVector.length v
val it : int = 3

PersistentVectors are immutable and therefor allow to create new version without destruction of the old ones.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
let v' = 
    v
    |> PersistentVector.conj "!!!" 
    |> PersistentVector.update 0 "hi" // replace existing value

PersistentVector.nth 0 v'
val it : string = "hi"
PersistentVector.nth 3 v'
val it : string = "!!!"

PersistentVector.nth 0 v
val it : string = "hello"
PersistentVector.length v
val it : int = 3
PersistentVector.length v'
val it : int = 4

// remove the last element from a PersistentVector
let v'' = PersistentVector.initial v'

PersistentVector.length v''
val it : int = 3

There a couple of interesting operations on PersistentVectors:

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
// Convert a sequence of values to a PersistentVectors
let intVector = PersistentVector.ofSeq [1..10]
val intVector : FSharpx.Collections.PersistentVector<int>

// Square all values in a PersistentVector
let intVector' = PersistentVector.map (fun x -> x * x) intVector
intVector'.[3]
val it : int = 256
namespace System
val v : obj
val v' : obj
val v'' : obj
val intVector : obj
val intVector' : obj
Fork me on GitHub