Automatic sequence listing

Is there a standard function for listing an F # sequence that works like Python enumerate () ?

Very easy to write from scratch:

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
    }

but I do not want to reinvent the wheel.

PS: too, I tried

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

but this part [0..10000]looks ugly.

+5
source share
2 answers

Is this what you want:

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")]

Or Hot 'n Spicy with FSharpx:

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

Well, actually, in FSharpx it is already available as Seq.index.

+1
source

All Articles