Search code examples
f#sequences

Automatic enumeration of an Sequence


Is there standard function to enumerate an F# sequence that works like Python's enumerate()?

It's 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 don't want to reinvent the wheel.

PS: also, I tried

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

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


Solution

  • I think maybe you want Seq.mapi or Seq.iteri.

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

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