2 people like it.

Slicing with ArraySegment

Slicing arrays without copying using .Net's ArraySegment struct

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
open System

type ArraySegment<'TItem> with
    member segment.Item(index) =
        segment.Array.[segment.Offset+index]
    member segment.GetSlice(start, finish) =
        let start = defaultArg start 0
        let finish = defaultArg finish segment.Count
        ArraySegment(segment.Array, segment.Offset + start, finish-start)

let xs = ArraySegment [|1..10|]
let ys = xs.[3..]
let zs = ys.[..2]
let five = zs.[1]
namespace System
Multiple items
type ArraySegment<'T> =
  struct
    new : array:'T[] -> ArraySegment<'T> + 1 overload
    member Array : 'T[]
    member Count : int
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member Offset : int
  end

Full name: System.ArraySegment<_>

--------------------
ArraySegment()
ArraySegment(array: 'T []) : unit
ArraySegment(array: 'T [], offset: int, count: int) : unit
val segment : ArraySegment<'T>
member ArraySegment.Item : index:int -> 'T

Full name: Script.Item
val index : int
property ArraySegment.Array: 'T []
property ArraySegment.Offset: int
member ArraySegment.GetSlice : start:int option * finish:int option -> ArraySegment<'T>

Full name: Script.GetSlice
val start : int option
val finish : int option
val start : int
val defaultArg : arg:'T option -> defaultValue:'T -> 'T

Full name: Microsoft.FSharp.Core.Operators.defaultArg
val finish : int
property ArraySegment.Count: int
val xs : ArraySegment<int>

Full name: Script.xs
val ys : ArraySegment<int>

Full name: Script.ys
val zs : ArraySegment<int>

Full name: Script.zs
val five : int

Full name: Script.five
Raw view New version

More information

Link:http://fssnip.net/ty
Posted:1 years ago
Author:Phillip Trelford
Tags: array , arraysegment , getslice