2013-12-13 27 views
2

我有以下代码。对于最后两个match,第一个period的类型为DateTime option,第二个的类型为int。为什么第二个没有选择?有效识别器的推断类型 - 一个是选项,另一个不是

let (|Integer|_|) (str: string) = 
    let mutable intvalue = 0 
    if Int32.TryParse(str, &intvalue) then Some(intvalue) 
    else None 

let (|DateyyMM|) (str: string) = 
    let mutable date = new DateTime() 
    if DateTime.TryParseExact(str, 
           "yyyyMM", 
           Globalization.DateTimeFormatInfo.InvariantInfo, 
           Globalization.DateTimeStyles.None, 
           &date) 
    then Some(date) 
    else None 

let (|ParseRegex|_|) regex str = 
    let m = Regex(regex).Match(str) 
    if m.Success 
    then Some (List.tail [ for x in m.Groups -> x.Value ]) 
    else None 

..... 
match url with 
| ParseRegex "....." [DateyyMM period] -> //period type is DateTime option 
...... 

match downloadLink.Url with 
| ParseRegex "....." [name; Integer period] -> // period type is int 
...... 

回答

3

第二种情况别无选择,因为你在声明的末尾添加_|

这是设置允许在比赛中的简写 - 这样,而不是

match x with 
|Some_long_function(Some(res)) -> ... 
|Some_long_function(None) -> ... 

你可以做

match x with 
|Some_long_function(res) -> ... 
|_ -> ... 

更多参见活动模式的MSDN页:http://msdn.microsoft.com/en-us/library/dd233248.aspx(尤其是部分图案的部分)

相关问题