F # how to write a function that provides a counter number in sequential order

So, if you go to the bank, there is a device from which you can withdraw the number.

I want to write such a function. Therefore, every time this function is called, we get the next number in the series.

So, if this function is called for the first time, we get 1. the second time we get 2 .... so on and so forth.

this is what i wrote 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 returns 1. I hope that since the sequence is a closure, every time I do this, I 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 ...

+4
source share
3 answers

Just for reference, if you want a version that uses sequences (like the first approach in your question), you can do this 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 just like the factory in Daniel's answer. This still uses a volatile state, but it is hidden inside a counter (which keeps the current state of the sequence between calls to MoveNext ).

In this simple case, I would use the version of Daniel, but the above can be convenient if you want to iterate over something else, and not just increase the number.

+7
source

You must return a function. And for this you need to transmit something every time, i.e. Your +1 should be delayed.

 let factory = let counter = ref 0 fun () -> counter.Value <- !counter + 1 !counter 

and now you get

 > factory();; val it : int = 1 > factory();; val it : int = 2 

This method has a good side effect that you completely hide the mutable reference cell inside the function, and therefore there is no way to interfere in any way with the counter.

+7
source

You need to move the variable outside the declaration. You also need to declare a function so that it is evaluated every time it is called.

 let mutable i = 1 let X() = i <- i + 1 i 

This ensures that the function is called every time and that the variable is correctly incremented.

+5
source

Source: https://habr.com/ru/post/1496379/


All Articles