OCaml 空全局变量
我想知道如何定义空! OCaml 中 Hashtbl
类型的全局变量? 我不想使用 Hashtbl.create
因为我不知道它的初始大小,并且出于性能原因我不想猜测初始大小。
基本上这个 Hashtbl
变量将在函数中被分配一个真正的 Hashtbl
,然后这个变量将在其他函数之间共享,所以我不想将它作为参数传递一直以来,因此我希望它是全球性的。
I'd like to know how do I define an empty! global variable of type Hashtbl
in OCaml?
I don't want to use Hashtbl.create
because I don't know its initial size and I don't want to guess the initial size for performance reasons.
Basically this Hashtbl
variable will be assigned a real Hashtbl
in a function and then this variable will be shared among other functions so I don't want to pass it around as an argument all the time hence I'd like it to be global.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
OCaml 中的哈希表会根据需要增长,因此您可以一开始就给 ag 最好的猜测,例如:
虽然您超出了初始数量,但它也会顺利工作,请查看本教程以获取更多信息 http://www.ocaml-tutorial.org/hashtbl
Hashtables in OCaml grow as needed, so you can just give a g best guess at first, for example :
Although you exceed the initial number but it will work smoothly too, check this tutorial for more info http://www.ocaml-tutorial.org/hashtbl
你所要求的都是可能的。您可以定义一个全局引用(这可以让您稍后将其分配)到哈希表选项(这可以让您首先将其保留为未初始化)。定义将如下所示:
初始化将是:
要使用它,您还必须解释如果尚未初始化它会发生什么:
在实践中,未初始化的变量违反 OCaml 哲学,只会让您的生活变得糟糕更难。我强烈建议您不要使用这种方法。我的两个建议是:
确定创建具有猜测大小的哈希表所造成的性能损失。开销可能比您想象的要小得多。
只需将哈希表传递到各处即可。它是一个参数,比选项引用短...
将哈希表和使用它的函数放在一个类中。
What you ask for is possible. You can define a global reference (this lets you assign it later on) to a hash table option (this lets you leave it uninitialized at first). The definition will look like this:
The initialization will be:
To use it, you will also have to explain what should happen if you haven't initialized it yet:
In practice, uninitialized variables are against the OCaml philosophy and will only make your life harder. I strongly advise you not to use this approach. My two suggestions would be:
Determine the performance loss caused by creating a hash table with a guessed size. The overhead might be much smaller than you think.
Just pass the hash table everywhere. It's a single argument, which is shorter than an option reference...
Put your hash table and the functions using it in a class.