I'd to use the String.Set.choose some_set
to pick a string from a set.
This method returns StringOption, but I want to use another method with the return value of the second, hence I'd like to cast the StringOption into string.
I know according to OCaml docs (link here) that Option.default
is supposed to do that but from some reason it's missing (although the Option
with all the rest of the methods exists).
Is there a way to workaround this or let my next method to accept StringOption?
Thanks,
First, those are not the OCaml docs :-) It's an add-on library. That particular repository is obsolete (like almost everything else on Sourceforge), and its Option module has been incorporated into OCaml Batteries Included as the BatOption module. Batteries is also an add-on library, but is one of the most widely used ones.
You can write your own function to extract a string from a string option, as long as you decide what you want to do when the value is actually
None
. In that case, there's no string of course.One possibility is just to raise an exception in that case. If you're positive there's always a string, the exception will never happen. If it does happen, you know you have a problem. So, you could write a function like this:
(This function works like
List.hd
; i.e., it's a partial function that raises an exception when the input is not valid.)You can also write your own version of
default
; it's an extremely simple function:A good way to get current OCaml docs is to go through ocaml.org.
Another very popular add-on library is Jane Street Core, described here. It has a function named
Option.value
that is similar to thedefault
function you were looking for. (In fact, the name seems a little better to me.)