The .NET standard library has the type ArraySegment<'T>
for this purpose. Unfortunately it doesn't have the methods Item
and GetSlice
that allow you to use the .[x]
and .[x..y]
syntaxes, respectively. But you can add them with an augmentation:
type System.ArraySegment<'T> with
member this.Item(x) =
if x < 0 || x >= this.Count then
raise (System.IndexOutOfRangeException("Index was outside the bounds of the array segment."))
this.Array.[x + this.Offset]
member this.GetSlice(start: int option, finish : int option) =
let start = defaultArg start 0
let finish = defaultArg finish (this.Count - 1)
if start < 0 || finish >= this.Count then
raise (System.IndexOutOfRangeException("Index was outside the bounds of the array segment."))
new ArraySegment<'T>(this.Array, this.Offset + start, finish - start + 1)