Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# type class persistent counter

Tags:

class

counter

f#

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
like image 505
iru Avatar asked Jan 05 '18 10:01

iru


2 Answers

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.

like image 104
Gus Avatar answered Oct 16 '22 08:10

Gus


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.

like image 32
CaringDev Avatar answered Oct 16 '22 09:10

CaringDev