【问题标题】:Why does F# fail to support extending system type with its type abbreviation?为什么 F# 不支持扩展系统类型及其类型缩写?
【发布时间】:2017-04-07 17:50:29
【问题描述】:

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

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

【问题讨论】:

  • 因为你不能。因为他们不是那样写的。因为。

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


【解决方案1】:

我认为 Will 的 glib 回答基本上是正确的 - 默认情况下未实现功能。然而,另一个可能的原因是类型缩写是有范围的,所以缩写的范围是否应该影响扩展的范围并不是很明显。例如:

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    相关资源
    最近更新 更多