perhaps I am being stupid here, so the more general question I want to ask is that how to declare a reference to a empty value of certain type in OCaml. Usually I declare a reference to a custom defined empty value, for example if I have a type type point = Point of (int * int)
I would declare a reference like this let a = ref (Point (0,0))
. However this is not satisfying because I have to ''come up" with a empty value myself. Also, if you look at the reference ``Stack'' module in the standard library (http://caml.inria.fr/pub/docs/manual-ocaml/libref/Stack.html), there is no empty value in it. How do you deal with this?
答案 0 :(得分:2)
If you really want it, you can do this:
let sr = ref (Stack.create ())
let () = Stack.push 42 !sr
OCaml's value restriction doesn't prevent it, it will initially have type '_a Stack.t ref, until you push into it.
But you hardly need it, Stack is already mutable.
答案 1 :(得分:1)
好吧,堆栈有一个空值,因为Stack.create ()
将创建一个空堆栈。关于您的一般问题,通常None
被用作空值。当然,这会自动将您的价值提升到选项中。但这是有意的,因为如果您将值创建为空,然后您将通过引用更新它而没有类型保证,那么您将更新它。
实施例
let p0 = ref None in
...
p0 := Some (Point (0,0));
...