2017-04-07 56 views
3

例如,如果我儘量延長int,與int不是類型的真實姓名,這個代碼將失敗:爲什麼F#不支持與它的類型縮寫擴展系統類型?

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

我必須使用System.Int32代替:

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

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

爲什麼能「T我用的類型縮寫int

+7

因爲你不能。因爲他們沒有這樣寫。因爲。 – Will

回答

6

我認爲會的圓滑的解釋是基本上是正確的 - 功能默認情況下沒有實現。然而,另一種可能的原因是該類型的縮寫是局部的,所以縮寫的範圍是否應影響擴展的範圍是不是很明顯。例如:

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?