Ocaml 中的全局变量

Sar*_*391 7 ocaml global-variables caml

我正在寻找一种在 ocaml 中定义全局变量的方法,以便我可以在程序中更改它们的值。我想要用户的全局变量是:

type state = {connected : bool ; currentUser : string};;
let currentstate = {connected = false ; currentUser = ""};;
Run Code Online (Sandbox Code Playgroud)

如何更改 connected 和 currentUser 的值并将新值保存在整个程序的同一变量 currentstae 中?

Bas*_*tch 5

要么声明一个可变记录类型:

type state = 
  { mutable connected : bool; mutable currentUser : string };;
Run Code Online (Sandbox Code Playgroud)

或者声明一个全局引用

let currentstateref = ref { connected = false; currentUser = "" };;
Run Code Online (Sandbox Code Playgroud)

(然后使用!currentstateref.connected...访问它)

两者都做不同的事情。可变字段可以发生变化(例如state.connected <- true;......但包含它们的记录保持相同的值)。引用可以更新(它们“指向”一些更新的值)。

您需要花几个小时阅读更多 Ocaml 书籍(或其参考手册)。我们没有时间教你大部分内容。

参考真的很像

type 'a ref = { mutable contents: 'a };;
Run Code Online (Sandbox Code Playgroud)

但使用语法糖(即中缀函数)来取消引用 ( !) 和更新 ( :=)