I want to add my own indexer to generic array type:
type 'T``[]`` with
member this.Item(x: string) = 1 // test
However, this gives a compile error "expression was expected to have type int but here has type string (FS0001)."
let a = [|1|]
let b = a.["aa"] // error: FS0001
let c = a.Item("aa") // this works.
I found this question which was asked 3 years ago and the answer suggested it's an FSharp bug. Want to confirm if it is still the case, or whether the specification has been updated since then?
Built-in classes like Array, Map and others are extendable also. Please note a very interesting thing. Built-in methods like filter , map and others – return new objects of exactly the inherited type PowerArray .
Array, Map, and other built-in classes are extendable. The most impressive thing is that built-in methods such as map , filter, and more - return new objects of literally the inherited type NumsArray .
We can extend the standard Array class and add new methods or redefine the existing ones. The of method on the new extended class creates a new extended array. The standard array methods like filter and map called on extended array return extended arrays.
Extending the JavaScript built-in object is not a good idea because if browser/JS has decided that they will provide the same method that you have extended, then your method will be override and the JS implementation (which may be difference from yours) would take over.
I got this question answered by Don Syme here:
The specification needs to be clarified that indexers for arrays may not be extended.
I'd say the suggestion to allow them is best tracked via http://fslang.uservoice.com. That said, it is not simple to do this, because array indexers are "built in" to the compiler and have no F# or IL metadata representation.
So it's not supported in Fsharp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With