【问题标题】:F# incomplete structured construct in my type我的类型中的 F# 不完整的结构化构造
【发布时间】:2021-03-23 13:09:35
【问题描述】:

我正在尝试在 F# 中实现 OrderedSet(您可以在其中按插入顺序获取项目的集合)。这是我第一次天真的尝试(我仍然必须处理传递给构造函数的 IEnumerable 中可能存在的重复项。比较器也仍然丢失)。

不过,我认为上述任何一项都不重要。我一直在尝试解决这个问题,据我从研究中收集到的信息,问题似乎与缩进或某处缺少括号有关。

如果我注释掉我实现 ISet 的尝试,则没有问题,这使我相信该部分具体有问题。代码如下:

open System
open System.Collections.Generic;

type public OrderedSet<'T> public (collection : IEnumerable<'T> option) as this =
    let mutable _set = SortedSet<int * 'T>()

    do
    if Option.isSome(collection) then
        let mapper (idx: int) (elem: 'T) = (idx, elem)
        do _set <- SortedSet<int * 'T>(Seq.mapi mapper collection.Value)

    interface ISet<'T> with
        member this.Count
            with get() = this._set.Count

【问题讨论】:

    标签: f#


    【解决方案1】:

    我只需要进行两项更改:

    • do 下缩进if
    • 删除_set前面的this.,因为它是let绑定的,不是类成员。

    当然,您还必须完成ISet 的实现。这是生成的代码:

    open System
    open System.Collections.Generic;
    
    type public OrderedSet<'T> public (collection : IEnumerable<'T> option) as this =
        let mutable _set = SortedSet<int * 'T>()
    
        do
            if Option.isSome(collection) then
                let mapper (idx: int) (elem: 'T) = (idx, elem)
                do _set <- SortedSet<int * 'T>(Seq.mapi mapper collection.Value)
    
        interface ISet<'T> with
            member this.Count
                with get() = _set.Count
    

    【讨论】:

    • 谢谢。我对do的概念有疑问
    • 如果您来自 C#,请将 do 块视为您的类的主要构造函数的主体。
    • 不过,当您分配给 _set 时,您不需要第二个 do
    • @Davi 更简单:interface ISet&lt;'T&gt; with member this.Count = _set.Count
    • 小事:不要在 f# 中为成员使用下划线前缀,因为下划线前缀通常表示虚拟标识符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多