2013-12-13 24 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(尤其是部分圖案的部分)

相關問題