Reputation: 966
How do I convert the string option data type to string in Ocaml?
let function1 data =
match data with
None -> ""
| Some str -> str
Is my implementation error free? Here 'data' has a value of type string option
.
Upvotes: 3
Views: 6069
Reputation: 66793
Another point is that the compiler would tell you if there's something wrong. If the compiler doesn't complain, you know that the types all make sense and that you have covered every case in your match
expression. The OCaml type system is exceptionally good at finding problems while staying out of your way. Note that you haven't had to define any types yourself in this small example--the compiler will infer that the type of data
is string option
.
A lot of the problems the compiler can't detect are ones that we can't detect either. We can't tell whether mapping None
to the empty string is what you really wanted to do, though it seems very sensible.
Upvotes: 3
Reputation: 41290
To answer your question, yes.
For this simple function, you can easily find it in Option
module. For example, Option.default
totally fits your purpose:
let get_string data =
Option.default "" data
There are many other useful functions for working with option types in that module, you should check them out to avoid redefine unnecessary functions.
Upvotes: 7