Search code examples
referenceocamlimperative-programming

How to declare a reference to a empty stack in OCaml?


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?


Solution

  • Well, stack has an empty value, since Stack.create () will create an empty stack. What concerning your general question, then usually None is used as an empty value. And of course this automatically lifts your value into option. But this is intentional, since if you're creating a value as an empty, and then you're going to update it though the reference there is no type guarantee, that you will ever update it.

    Example

    let p0 = ref None in
    ...
    p0 := Some (Point (0,0));
    ...