Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is global scoping done in F#

I need to create a collection in F# that has a key value pair and is global in scope.

like image 314
Guy Coder Avatar asked Mar 23 '12 17:03

Guy Coder


People also ask

What is the scope of a global variable?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block. They all have Global Scope: var x = 2; // Global scope.

What is the scope of global variable in C?

Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.

What does global in scope mean?

In a programming environment, the global scope is the scope that contains, and is visible in, all other scopes.

How does scope work in C?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.


2 Answers

You can do this:

[<AutoOpen>]
module Globals =
  let map = System.Collections.Generic.Dictionary<_,_>()

Then use it unqualified throughout your program:

map.Add(1, "a")
map.Add(2, "b")
map |> Seq.iter (fun (KeyValue(k, v)) -> printfn "Key: %d, Value: %s" k v)
like image 109
Daniel Avatar answered Nov 02 '22 04:11

Daniel


depending on what kind of project you are doing the best method might be do just declare it in a module:

module GlobalVals =

    let myCollection = .... // whatever

you can just use it with

GlobalVals.myCollection...
like image 21
Random Dev Avatar answered Nov 02 '22 05:11

Random Dev