简体   繁体   中英

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 ?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM