F# how to write a function which provides a counter number in serial order

f#

Solution

Just for a reference, if you wanted a version that uses sequences (just like the first approach in your question), you can do that using the `IEnumerable` interface:

let factory = 
  // Infinite sequence of numbers & get enumerator
  let numbers = Seq.initInfinite id
  let en = numbers.GetEnumerator()
  fun () -> 
    // Move to the next number and return it
    en.MoveNext() |> ignore
    en.Current

It behaves the same way as `factory` in Daniel's answer. This still uses mutable state - but it is hidden inside the enumerator (which keeps the current state of the sequence between `MoveNext` calls).

In this simple case, I'd use Daniel's version, but the above might be handy if you want to iterate over something else than just increasing numbers.

Problem

So if you go to a bank there is a device from which you can pull a number out. I want to write a function like that. So everytime this function is called we get a next number in the series. So if this function is called first time, we get 1. second time we get 2.... so on and so forth. this is what I have written so far ``` let X = let myseq = seq {1 .. 100} let GetValue = Seq.head (Seq.take 1 myseq) GetValue;; let p = X;; p;; p;; p;; ``` But it always return 1. My hope was that since the sequence is a closure, everytime I do a take, I will get the next number. I also tried this ``` let X = let mutable i = 1 let GetValue = i <- i + 1 i GetValue;; let p = X;; p;; p;; p;; ``` This one only prints 2...

Original source