Gentlefolk,
Old time procedural/deterministic programmer battling with F# functional....
I require some counters to record counts from various areas of a program. The following code compiles clean and appears to work but "ctr" is never incremented.
Any help appreciated, Ian
type Count() as this =
let mutable ctr = 0
do
printfn "Count:Constructor: %A" ctr
member this.upctr : int =
let ctr = ctr + 1
printfn "inCount.upctr %d" ctr
ctr
let myCount = new Count()
printfn "MyCtr1 %d" (myCount.upctr)
let fred = myCount.upctr
let fred = myCount.upctr
The value ctr
is mutable. Use:
ctr <- ctr + 1 // this will mutate the value contained in ctr
instead of
// this will create a new binding which is not mutable
// and will shadow the original ctr
let ctr = ctr + 1
Also notice the warning that is telling you that you don't need as this
in the type declaration.
You could also create a threadsafe counter like this:
let counter() =
let c = ref 0
fun () ->
System.Threading.Interlocked.Increment(c)
and use
let countA = counter()
let countB = counter()
countA() |> printfn "%i" // 1
countA() |> printfn "%i" // 2
countB() |> printfn "%i" // 1
Wrap this in a type or module, if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With