MiP
MiP

Reputation: 6462

Why does F# fail to support extending system type with its type abbreviation?

For example, if I try to extend int, with int is not the true name of the type, this code will fail:

type int with
member this.IsEven = this % 2 = 0

I must use System.Int32 instead:

type System.Int32 with
member this.IsEven = this % 2 = 0

//test
let i = 20
if i.IsEven then printfn "'%i' is even" i

Why can't I use the type abbreviation int?

Upvotes: 3

Views: 91

Answers (1)

kvb
kvb

Reputation: 55185

I think Will's glib answer is basically right - features are unimplemented by default. However, another possible reason is that type abbreviations are scoped, so it's not immediately obvious whether the scope of the abbreviation should influence the scope of the extension. For example:

module X =
    type t = int

module Y =
    // imagine we could hypothetically do this
    type X.t with
        member i.IsEven = i % 2 = 0

open Y
fun (x:System.Int32) -> x.IsEven // should this compile even though t isn't in scope here?

Upvotes: 6

Related Questions