F # array with O (1) finding and O (1) slice

I need a Array type data structure that supports

a.[i] 

in a time O (1) and

 a.[i..j] 

also in time O (1).

O (1) updates are not required. Really, all I need is a constant array with the concept of on-site or subarray.

I could, of course, to build such a thing of Array , but I would be happier if I could use one that already exists?

+6
source share
1 answer

.NET standard library has type ArraySegment<'T> for this purpose. Unfortunately, it does not have methods Item and GetSlice , which allow to use the syntax .[x] and .[x..y] , respectively. But you can add them to the increase:

 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) the bounds of the array segment.")) 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) finish: int option) = 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) 
+12
source

All Articles