F # Use the list [] operator in a class?

I have my own class in F #, and I want to implement the list operator [] in such a way that

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

I can’t find it on the Internet - I probably don’t know the right word to search for ... thanks in advance

+3
source share
3 answers

You just need to implement the Itemindexed property . For instance.

type MyClass() =
  member x.Item with get(i:int) = (* some logic involving i here *)
+5
source

If you start with the F # help system and go to members , one of the topics is indexed properties .

+5
source

, F # slicing ( MSDN ). , , m.[0], , m.[0..5] m.[5..]. ( ).

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

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 defaultArgto specify 0 as the default value.

+5
source

Source: https://habr.com/ru/post/1742204/


All Articles