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

 

使用条件判断:&&||

基本的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

 

目录传送门     

转载于:https://www.cnblogs.com/pandora/archive/2010/08/31/FSharp_UsingOption.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值