Class F # constant counter

Noble,

An old-fashioned procedural / deterministic programmer struggling with F # functionality ....

I need some counters to record samples from different areas of the program. The following code compiles and works, but "ctr" never grows.

Any help was appreciated, Yang

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
+4
source share
2 answers

The value is ctrvariable. Using:

ctr  <- ctr + 1  // this will mutate the value contained in ctr

instead

// this will create a new binding which is not mutable
// and will shadow the original ctr
let ctr = ctr + 1  

Also pay attention to the warning, which says that you do not need as thisa type declaration.

+3
source

You can also create a thread safety counter:

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

If necessary, wrap it with a type or module.

+3
source

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


All Articles