4

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 Answers 3

6

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 *)
Sign up to request clarification or add additional context in comments.

2 Comments

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)
@ak refer to F#'s source code. A good one is its matrix implementation in matrix.fs.
6

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

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.