views:

114

answers:

3

I have a custom class in F# and I want to implement the [] list operator such that

let myClass = new myClassObj()
let someVal  = myClass.[2]

I can't seem to find this on the web - I probably don't know the right term to search for... thanks in advance

+3  A: 

You just need to implement an Item indexed property. E.g.

type MyClass() =
  member x.Item with get(i:int) = (* some logic involving i here *)
kvb
many thanks - where would I go to find more somethign like this out (searching the web on [] or index or list doesn't turn up much appealing info)
akaphenom
@ak refer to F#'s source code. A good one is its matrix implementation in matrix.fs.
Yin Zhu
+2  A: 

If you start at the F# language reference, and go to members, one of the topics is indexed properties.

Brian
+2  A: 

It is worth adding that F# also supports slicing syntax (which isn't mentioned on the indexed properites MSDN page). It means that you can index not only a single element such as m.[0] but also a slice such as m.[0..5] or an unbounded range m.[5..]. This is quite useful for various numerical data types (such as matrices).

To support this feature, the type must define GetSlice method. The following example demonstrates this using a 2D scenario:

type Foo() = 
  member x.GetSlice(start1, finish1, start2, finish2) =
    let s1, f1 = defaultArg start1 0, defaultArg finish1 0
    let s2, f2 = defaultArg start2 0, defaultArg finish2 0
    sprintf "%A, %A -> %A, %A" s1 s2 f1 f2

> let f = new Foo()    
  f.[1.., 1..10];;
val it : string = "1, 1 -> 0, 10"

The arguments are of type int option and here we use defaultArg to specify 0 as the default value.

Tomas Petricek