Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend built-in array's indexer?

Tags:

f#

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?

like image 907
trek42 Avatar asked Apr 24 '14 02:04

trek42


People also ask

Can you extend a built-in type?

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 .

Is it possible to extend built-in classes in JS?

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 .

Can array in JavaScript be extended?

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.

Why is extending built-in JavaScript objects not a good idea?

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.


1 Answers

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.

like image 189
trek42 Avatar answered Oct 30 '22 01:10

trek42