您的位置:首页 > 其它

F#教程:Pattern Match

2010-07-11 13:49 120 查看
前言:最近在了解F#,无意中看到一个日文的教程(http://techbank.jp/Community/blogs/gushwell/default.aspx),觉得很不错,所以希望可以和大家一起分、学习。
这回我们要挑战下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是一样的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: