Use options (option)
type 'T option =
| None
| Some of 'T
Let's look at an example:
> let people = [ ("Adam", None);
("Eve" , None);
("Cain", Some("Adam","Eve"));
("Abel", Some("Adam","Eve")) ];;
val people : (string * (string *string) option) list
Use pattern matching (patterns matching) to generate option:
> let showParents (name,parents) =
match parents with
| Some(dad,mum) -> printfn "%s has father %s, mother %s" name dad mum
| None -> printfn "%s has no parents!" name;;
val showParents : (string * (string * string) option) -> unit
> showParents people.[0];;
Adam has no parents
val it : unit = ()
Some useful methods for option:
Method |
Type |
Describe |
Option.get |
' t option-> ' t |
Returns the value of a some type. or throw an exception |
Option.isnone |
' T option-> bool |
Returns whether an option is None |
Option.map |
(' t-> ' u)-> ' t option-> ' u option |
If none is returned, none. If it is some (x), return some (f x), F is the given function |
Option.iter |
(' t-> Unit]-> ' t option-> Unit |
Executes the specified method for option some type. |
Some examples:
> Option.map(fun x->x) a;;
val it : (string * string) option = Some ("aa", "bb")
> Option.map(fun x-> match x with | (first,second) -> first) a;;
val it : string option = Some "aa"
> Option.map(fun x-> match x with | (first,second) -> second) a;;
val it : string option = Some "bb"
>
> Option.iter(fun x-> match x with | (first:string,second) -> printfn "%s" (first+second)) a;;
aabb
val it : unit = ()
>
Use option type for control
Look at this example:
let fetch url =
try Some (http url)
with :? System.Net.WebException -> None
The HTTP function is the method that gets the HTML defined in the previous section. Throws a exception in the case of none. A successful access returns a some value, which is the value of the option type. We can then use option values for pattern matching:
> match (fetch "http://www.nature.com") with
| Some text -> printfn "text = %s" text
| None -> printfn "**** no web page found";;
text = <HTML> ... </HTML> (note: the HTML is shown here if connected to the web)
val it : unit = ()