F#教程:Pattern Match


这回我们要挑战下match语句:

let s = "red"
match s with
| "red" -> printfn "红"
| "white" -> printfn "白"
| _ -> printfn "其他颜色"

  其中,分支的顺序很重要。

  _ 可以匹配一切。如果把它写在最开始,其他的条件就不会被匹配到了。

  但是,如果写成如下这样:

let n = 2
match n with
| 1 -> printfn "1"
| 2 -> printfn "2"

  编译时就会有一个警告: Incomplete pattern matches on this expression. For example, the value '0' will not be matched。说的很明白吧,分支没有覆盖所有情况。改写后如下:

let n = 2
match n with
| 1 -> printfn "1"
| 2 -> printfn "2"
| _ -> printfn " "

  但是通过这种方法,1、2以外的值是无法处理的。解决办法如下:

let n = 2
match n with
| 1 -> printfn "1"
| x -> printfn "%A" x

  其中,1以外的情况也处理了。通过将其值带入到x,就可以引用到该值。要注意的是:x只是一个符号,z、y以及hoo等等都是可以的。

  此外,如下的代码也是可以的:

let    s = [1;2;3;4;5]
match s with
| [] -> printfn "空"
| x::xs -> printfn "%A %A" x xs

  运行结果是:

  1 [2; 3; 4; 5]

  这样,list的第一个元素和其他元素就可以分开操作了。这点和Haskell是一样的。


« 
» 
快速导航

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