为什么F#无法支持扩展系统类型及其类型缩写?

时间:2017-04-07 17:50:30

标签: .net casting f# functional-programming language-design

例如,如果我尝试扩展intint不是该类型的真实名称,则此代码将失败:

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

为什么我不能使用缩写int

1 个答案:

答案 0 :(得分:6)

我认为Will的滑稽答案基本上是正确的 - 默认情况下功能未实现。但是,另一个可能的原因是类型缩写是作用域的,因此缩写的范围是否应该影响扩展的范围并不是很明显。例如:

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?