Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# overwrite array access operator .[]

Tags:

f#

in F#, I want to make a type of indexed array, so I can access the element by either .[i] or .[index_names] and by slice notation with index .. Is it possible to overwrite .[] like this? thanks.

like image 751
fsharpts Avatar asked May 28 '11 13:05

fsharpts


1 Answers

define overloaded indexer in your type:

type MyIndexedArray<'T>() = 
    member this.Item(i : int) : 'T = Unchecked.defaultof<_>
    member this.Item(name : string) : 'T = Unchecked.defaultof<_>
    member this.GetSlice(a : int option, b : int option) : 'T = Unchecked.defaultof<_>

let arr = new MyIndexedArray<int>()
let a = arr.[1]
let b = arr.["name"]
let c = arr.[1..2]
let d = arr.[1..]
let e = arr.[..3]
let f = arr.[*]
like image 61
desco Avatar answered Sep 19 '22 05:09

desco