Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++-like static variables inside a F# function

Is there some analog in F#? Something like

let f () =
   let mutable static a = 0
   ...

?

like image 219
Oleg Leonov Avatar asked Dec 02 '25 21:12

Oleg Leonov


1 Answers

If you desugar let f () = ... to let f = fun () -> ..., you can put the declaration of a inside of the definition of f, but before the beginning of the function. This will make the function close over a while keeping a local to f. The problem with this is that you may not close over mutable variables, so you'll need to use a ref instead:

let f =
    let a = ref 0
    fun () ->
        ....
like image 67
sepp2k Avatar answered Dec 06 '25 17:12

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!