There are a couple of very-helpful common operations on values of type 'a option
that would be useful for you here.
The first is a function that takes another function and an option and, if that option is Some x
rather than None
, applies the function to x
. This has a couple of different names, depending on the implementer. I tend to call it “apply” or “apply_if_some” when I use it in my codebases (it’s not in the stdlib), and it looks like this:
let apply_if_some (f : 'a -> unit) = function
| Some x -> f x
| None -> ()
In your case, you could use this function to apply_if_some print_int (fetch_xs_max hs)
. That said, going this route won’t print anything if your option is None
.
The next function that could be useful is one that takes a default value, and fetches either x
if the option is Some x
, or else your default value if the option is None
. It’s also not in the stdlib, and I tend to call it “get_or_default” when I use it:
let get_or_default (default_value: 'a) = function
| Some x -> x
| None -> default_value
In your case, you could also use this function to print_int (get_or_default 0 (fetch_xs_max hs))
, but then in the case that the largest value in your array is 0 at some point, you won’t really be able to tell, since 0 is the default “I found nothing” value. The same applies if you use -1, or really any other int value.
So the next function that could be useful is basically “map”, but for 'a option
s. I’m really surprised this one isn’t in the stdlib, honestly. It looks like this:
let option_map f = function
| Some x -> Some (f x)
| None -> None
So then, using most of these functions together, you could do this:
fetch_xs_max hs
|> option_map string_of_int (* Convert the int option to a string option *)
|> get_or_default "None" (* Get the stringified-int out of the option, or else the string "None" *)
|> print_endline (* Print the result *)