Oleg Leonov
Oleg Leonov

Reputation: 345

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

Is there some analog in F#? Something like

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

?

Upvotes: 3

Views: 278

Answers (2)

sepp2k
sepp2k

Reputation: 370455

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 () ->
        ....

Upvotes: 8

John Palmer
John Palmer

Reputation: 25526

The simplest analog is to put the let before the function:

let mutable static a = 0
let f () =

If you really wanted to hide the variable you could encase the entire thing in a parent module.

Otherwise, sequence expressions allow for remembering variables in functions, but are a pretty significant change.

Some other ideas - hide inside a class:

type t() = 
    static let mutable t =  1
    static member f() = 1

or a module

module  t = 
    let mutable private t =  1
    let f() = 1

in the module approach, f is visible, but t is not

Upvotes: 4

Related Questions