Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic enumeration of an Sequence

Tags:

f#

sequences

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.

like image 636
qehgt Avatar asked May 24 '12 18:05

qehgt


People also ask

Which is an automatic sequence?

In mathematics and theoretical computer science, an automatic sequence (also called a k-automatic sequence or a k-recognizable sequence when one wants to indicate that the base of the numerals used is k) is an infinite sequence of terms characterized by a finite automaton.

What is enumeration sequence?

Sequence enumeration is a way of specifying and mapping stimuli and responses of an embedded system. This approach considers all permutations of input stimuli. Sequence enumerations consist of a list of prior stimuli and current stimuli as well as a response for that particular stimuli given the prior history.


2 Answers

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

like image 122
Brian Avatar answered Oct 13 '22 18:10

Brian


This is 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's already available as Seq.index.

like image 44
johv Avatar answered Oct 13 '22 18:10

johv