【F#2.0系列】使用选项(Option)


使用选项(Option)

type 'T option =
    | None
    | Some of 'T

  下面看一个例子:

> let people = [ ("Adam", None);
                 ("Eve" , None);
                 ("Cain", Some("Adam","Eve"));
                 ("Abel", Some("Adam","Eve")) ];;
val people : (string * (string *string) option) list

  使用模式匹配(Pattern matching)来生成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 = ()

  Option的一些有用的方法:

  方法   类型   描述
  Option.get   'T option -> 'T   返回一个Some类型的值。或抛异常
  Option.isNone   'T option -> bool   返回一个Option是否是None
  Option.map   ('T -> 'U) -> 'T option -> 'U option   如果是None,就返回None。如果是Some(x),返回Some(f x),f是给定的函数
  Option.iter   ('T -> unit) -> 'T option -> unit   对Some类型的Option执行指定的方法。


  一些例子:

> 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 = ()
 
> 

  使用Option类型进行控制

  看这个例子:

let fetch url =
    try Some (http url)
    with :? System.Net.WebException -> None

  http函数是在之前章节定义的获取html的那个方法。在None的情况下抛出一个exception。成功的访问会返回一个Some值,也就是Option类型的值。然后我们就可以使用Option值来进行模式匹配:

> 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 = ()


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3