5

是否有标准函数来枚举像 Python 的enumerate()一样工作的 F# 序列?

从头开始编写非常容易:

let enumerate (sq : seq<'T>) = seq {
    let rec loop (e : IEnumerator<'T>) index = seq {
        if e.MoveNext() then 
            yield (index, e.Current)
            yield! loop e (index+1) 
    }

    use enum = sq.GetEnumerator()
    yield! loop enum 0
    }

但我不想重新发明轮子。

PS:也,我试过了

let seasons = ["Spring"; "Summer"; "Fall"; "Winter"]
for x in Seq.zip [0..100000] seasons do
    printfn "%A" x

但这[0..10000]部分看起来很难看。

4

2 回答 2

4

我想也许你想要Seq.mapiSeq.iteri

http://msdn.microsoft.com/en-us/library/ee340431.aspx

http://msdn.microsoft.com/en-us/library/ee370541

于 2012-05-24T18:54:52.650 回答
1

这就是你想要的:

module Seq =
    let inline enumerate source = Seq.mapi (fun i x -> i,x) source

> ["a"; "b"] |> Seq.enumerate;;
val it : seq<int * string> = seq [(0, "a"); (1, "b")]

或 FSharpx 的 Hot 'n Spicy:

let enumerate source = Seq.mapi (curry id) source

好吧,实际上,在 FSharpx 中,它已经可以作为Seq.index.

于 2013-12-18T00:17:32.960 回答