49 people like it.

Support slicing operator

The snippet shows how to support slicing in a type. Slicing allows you to get for example a 2D sub-matrix of a matrix and is implemented by adding GetSlice member.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
type Indexable() =  
  /// Returns a 2D slice. Arguments are optional and will be None
  /// when the user writes for example x.[1 .. , 1 .. ]  
  member x.GetSlice(start1, finish1, start2, finish2) = 
    let s1, f1 = defaultArg start1 0, defaultArg finish1 100
    let s2, f2 = defaultArg start2 0, defaultArg finish2 100
    // Return a string with the range of the slice
    sprintf "[%A, %A] -> [%A, %A]" s1 s2 f1 f2 
 
// Returns [1, 0] -> [100, 10]
let r = new Indexable()     
r.[1.., ..10]
Multiple items
type Indexable =
  new : unit -> Indexable
  member GetSlice : start1:int option * finish1:int option * start2:int option * finish2:int option -> string

Full name: Script.Indexable

--------------------
new : unit -> Indexable
val x : Indexable
member Indexable.GetSlice : start1:int option * finish1:int option * start2:int option * finish2:int option -> string

Full name: Script.Indexable.GetSlice


 Returns a 2D slice. Arguments are optional and will be None
 when the user writes for example x.[1 .. , 1 .. ]
val start1 : int option
val finish1 : int option
val start2 : int option
val finish2 : int option
val s1 : int
val f1 : int
val defaultArg : arg:'T option -> defaultValue:'T -> 'T

Full name: Microsoft.FSharp.Core.Operators.defaultArg
val s2 : int
val f2 : int
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
val r : Indexable

Full name: Script.r
Raw view Test code New version

More information

Link:http://fssnip.net/F
Posted:13 years ago
Author:Tomas Petricek
Tags: slice , matrix , indexing , getslice