I keep seeing this problem, chances are you might also have seen it, it often happens when initializing something, and is not specific to OCaml. The problem can be summarized as this:
When the application is starting, you often need some values to proceed to the next step, (these values can come from a config file, or from a HTTP request, etc.), if these values are not there, then there is no strictly better alternatives than terminating the application. (an example: you will need the password to the database if your application is database-focused and non-interactive).
Solution 1, is to use a
ref to an
option, it’s doable, but as far as I can see, it’s a bit of stretch, because the value will always be
Some _ after the first time you turn it from
Some _, and all codes that use this value has to match on
None, you ends with lots of impossible branches if this value gets used a lot.
Solution 2, is to wrap solution 1 with a function like this:
let get_value r =
match !r with
| Some x -> x
| None -> failwith "yay! null reference"
but this solution kinds of introducing the
null back into runtime.
I guess what I’m looking for is some kind of “inference over time”: after a certain point in the execution of a program, some nullable values are guaranteed to be non-null.
Does something for this kind of purpose exist? It’s painful when you don’t know what to type into the Google search box.
Sometime I can rearrange the code flow to avoid this, (ending with more code), sometime I have no better alternatives than the solutions above.