Reputation: 345
Is there some analog in F#? Something like
let f () =
let mutable static a = 0
...
?
Upvotes: 3
Views: 278
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
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