在外部类型的Fsharp中实现IEnumerable

时间:2012-02-24 14:55:37

标签: f# ienumerable sequence anonymous-types

我正在尝试在不实现它的外部类型上实现ToEnumerable属性。我无法让代码工作。

所以我愚蠢地添加了一个无类型的 GetEnumerator 属性,并添加了ToComparable的代码以获得指导。但是,我不知道如何为计数器存储可变状态。

pb是匿名类吗?

你会怎么做?

open System
open System.Collections
open System.Collections.Generic

type Bloomberglp.Blpapi.Element with
     //**WORKS OK**
     member this.ToComparable:IComparer<Bloomberglp.Blpapi.Element> =   { 
        new IComparer<Bloomberglp.Blpapi.Element> with 
           member this.Compare(x, y) = x.NumValues.CompareTo(y.NumValues) 
     }

     //**WORKS (sort of) OK without storing the state**
     member this.GetEnumerator2:IEnumerator =  {
        //let mutable i =0
        new IEnumerator with
              member this2.Reset() = 
                 i <- 0;
                 ()
              member this2.MoveNext() = 
                 if i < n then 
                    i <- i + 1
                    true
                 else
                    false
              member this2.Current 
                 with get() =
                    this.GetElement(0) :> obj
     }

2 个答案:

答案 0 :(得分:2)

假设NumValues是计数,你可以这样做:

type Bloomberglp.Blpapi.Element with
  member this.GetEnumerator() = 
    (Seq.init this.NumValues this.GetElement).GetEnumerator()

这会返回IEnumerator<'T>,其中'TGetElement的返回类型。

答案 1 :(得分:1)

回到最初为类型添加ToEnumerable属性的想法,我可能将属性命名为AsEnumerableAsSeq,因为Seq是IEnumerable的F#术语,并实现它像这样的东西:

type Bloomberglp.Blpapi.Element with
    member this.AsEnumerable =
        seq { for i = 0 to this.NumValues - 1 do
                  yield this.GetElement(i) }

或者你可以用Seq.init做丹尼尔建议:

type Bloomberglp.Blpapi.Element with
    member this.AsEnumerable =
        Seq.init this.NumValues this.GetElement