是否有标准函数来枚举一个像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]
部分看起来很难看。
答案 0 :(得分:4)
我想也许你想要Seq.mapi
或Seq.iteri
。
答案 1 :(得分: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一起辛辣:
let enumerate source = Seq.mapi (curry id) source
嗯,实际上,在FSharpx中它已经可以Seq.index
。