【问题标题】:How does F# know that bitArray elements are bool while enumerating in seq builder?F# 在 seq builder 中枚举时如何知道 bitArray 元素是 bool?
【发布时间】:2019-01-15 22:59:16
【问题描述】:
    seq{
        for bit in BitArray(10) do 
        yield bit
    }

bit 属于 bool 类型。我检查了 ILSpy 并在生成的一个闭包中添加了一个显式转换。

BitArray 仅实现普通(非通用)IEnumerable。 F# 怎么知道是bool

【问题讨论】:

    标签: f#


    【解决方案1】:

    According to the F# 4.1 specification's Section 6.5.6 Sequence Iteration Expressions,如果IEnumerable 具有非Item 属性和非object 类型(突出显示我的),F# 甚至对非泛型IEnumerable 进行强制转换:

    以下形式的表达式是序列迭代 表达式:

    for pat in expr1 完成 expr2 完成

    pat的类型与枚举器值上Current属性的返回类型相同.然而, 如果 Current 属性具有返回类型 obj 和集合类型 ty 有一个具有更具体(非对象)返回类型的 Item 属性 ty2,改为使用类型ty2,并插入动态转换 将 v.Current 转换为 ty2

    If we look at the source code for BitArray,我们看到它确实有一个Item 类型为bool 的属性:

    public bool this[int index] {
            get {
                return Get(index);
            }
            set {
                Set(index,value);
            }
    }
    

    因此,F# 将在迭代时显式转换为 bool

    【讨论】:

    • 这是我的猜测,但我在规范中找不到。感谢您找到它。
    猜你喜欢
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多