Arrays 具有O(1)查找和O(1)切片的F#数组
我需要一个类似数组的数据结构,支持Arrays 具有O(1)查找和O(1)切片的F#数组,arrays,f#,functional-programming,slice,Arrays,F#,Functional Programming,Slice,我需要一个类似数组的数据结构,支持 a.[i] 在时间O(1)和 同样在时间O(1)中 O(1)不要求更新。实际上,我所需要的只是一个带有就地切片或子数组概念的常量数组 当然,我可以从数组构造这样的东西,但是如果我可以使用一个已经存在的数组,我会更高兴。基于此目的,.NET标准库有这样的类型。不幸的是,它没有方法Item和GetSlice,分别允许您使用[x]和[x..y]语法。但您可以添加一个扩展: type System.ArraySegment<'T> with m
a.[i]
在时间O(1)和
同样在时间O(1)中
O(1)不要求更新。实际上,我所需要的只是一个带有就地切片或子数组概念的常量数组
当然,我可以从
数组
构造这样的东西,但是如果我可以使用一个已经存在的数组,我会更高兴。基于此目的,.NET标准库有这样的类型。不幸的是,它没有方法Item
和GetSlice
,分别允许您使用[x]
和[x..y]
语法。但您可以添加一个扩展:
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)
键入System.ArraySegment(this.Array,this.Offset+start,finish-start+1)
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)