Hi,
First, i cannot understand what this mean and where we can use these expressions;
let a = None
let b = Some 10 what some mean ?
let b=10
let c = Some true
let d = Some "ok"
Second,
how can write this in ocaml
let matchfunction x y z= match x y z with | | with the condition that function has type int->int->int-> int=
Some is a constructor of the option type. The definition is roughly:
type 'a option = Some of 'a | None
Which means that it either holds a value of some unspecified ('a) type (Some) or it is empty (None).
So Some 10 is an int option, the Some true is a bool option and the Some "ok" is a string option.
If you want to write a function int -> int -> int -> int you need to create a function which takes 3 arguments, uses them as ints and returns another int. Then the type checker will be able to resolve 'a -> 'b -> 'c -> 'd (the most generic signature) to ints.
beginners question. But how do you extract the value if it does have a value?
I tried this but obviously it shouldnât work and it doesnât but it portrays what I was going for:
(* Which means that it either holds a value of some unspecified ('a) type (Some) or it is empty (None). *)
type 'a option =
| Some of 'a
| None;;
let some_ten = Some 10;;
let get_option some_val =
match some_val with
| Some a -> a
| None -> None;;
let ten = get_option some_ten;;
What do you expect the type of the resulting function to be? The first case (Some a -> a) suggests that it should be 'a, but the second case suggests that it should be 'a option. But itâs not allowed to be both.
There are (at least) a few options here:
Have your function take a default value of type 'a to use in the None case. The stdlib function Option.value does this.
Have your function raise an exception in the None case.
Instead of using a function to extract the value, in some cases you might want to do very different things depending on whether the value is present. So the code that uses the 'a value goes in the Some case, and you write different code that doesnât depend on the value in the None case.
Iâm not sure I follow. Iâve described three ways of getting the value from an option. But Iâm happy to elaborate or give examples, or maybe you could say more about what youâre trying to do.
let get_option some_val = match some_val with
| Some a -> a
| None -> raise Not_found
This is Leviâs item #2. This throws an exception at runtime if the option argument is actually None. If youâre OK with that, then sure, that works. Itâs analogous to âindexingâ in some languages where e.g. if you do arr[i] and arr has no element at that index then it throws a runtime exception.
If youâre not OK with that (and many people arenât because theyâre trying to eliminate runtime exceptions as much as possible), then you could give the function a âdefaultâ parameter:
let get_option default some_val = match some_val with
| Some a -> a
| None -> default