Global variables in Ocaml
Asked Answered
I

2

9

I am looking for a way to define global variables in ocaml so that i can change their value inside the program. The global variable that I want to user is:

type state = {connected : bool ; currentUser : string};;
let currentstate = {connected = false ; currentUser = ""};;

How can I change the value of connected and currentUser and save the new value in the same variable currentstae for the whole program?

Inventive answered 10/12, 2013 at 20:52 Comment(1)
It is not possible to assign to a variable in ML.Audile
A
5

Either declare a mutable record type:

type state = 
  { mutable connected : bool; mutable currentUser : string };;

Or declare a global reference

let currentstateref = ref { connected = false; currentUser = "" };;

(then access it with !currentstateref.connected ...)

Both do different things. Mutable fields can be mutated (e.g. state.connected <- true; ... but the record containing them stays the same value). References can be updated (they "points to" some newer value).

You need to take hours to read a lot more your Ocaml book (or its reference manual). We don't have time to teach most of it to you.

A reference is really like

type 'a ref = { mutable contents: 'a };;

but with syntactic sugar (i.e. infix functions) for dereferencing (!) and updating (:=)

Aurochs answered 10/12, 2013 at 20:54 Comment(1)
I wouldn't think of ! and := as syntactic sugar, they're just ordinary functions.Anosmia
K
2

type state = {connected : bool ; currentUser : string};; let currentstate = {connected = false ; currentUser = ""};;

can be translated to :

type state = {connected : bool ref ; currentUser : string ref };;
let currentstate = {connected = ref false ; currentUser = ref ""};;

to assign value :

(currentstate.connected) := true ;;
- : unit = ()

to get value :

!(currentstate.connected) ;;
- : bool = true 

you can also pattern match on its content.

read more about ref here

Karinkarina answered 18/12, 2013 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.