使用选项(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 = ()

 

使用条件判断:&&||

基本的F#控制符为if/then/elif/else。举例:

let round x =

    if x >= 100 then 100

    elif x < 0 then 0

    else x

 

条件判断其实是模式匹配(pattern matching)的缩写;上例可以写为下面的形式:

let round x =

    match x with

    | _ when x >= 100 -> 100

    | _ when x < 0    -> 0

    | _               -> x

 

使用&&||

let round2 (x, y) =

    if x >= 100 || y >= 100 then 100,100

    elif x < 0 || y < 0 then 0,0

    else x,y

 

目录传送门     

相关文章: