2012-08-05 119 views
4

您好,我寫了下面的代碼。F#模式匹配when子句

我的目標是編寫一個名爲getWoeid的函數,它將檢查命令行參數是否爲具有1個元素的數組,並且該元素是整數。

我的代碼有效......但我調用TryParse方法兩次......我想知道是否有一種方法可以只調用一次。

此外,您是否可以確認這種使用模式匹配驗證命令行參數的方式是否正確?

open System; 
open System.Xml; 

let getWoeid args = 
    let retVal = 0 
    match args with  
    | [|a|] when fst (Int32.TryParse(a)) = true -> 
     printfn "%s" "Starting the processing for woeid " 
     Some(snd (Int32.TryParse(a)))  
    | _ -> failwith "Usage XmlRead WOEID"  

[<EntryPoint>] 
let main args = 
    let woeid= 
    try 
     getWoeid args   
    with 
     | Failure (msg) -> printfn "%s" msg; None 

    0 

回答

12

可以定義有源圖案:

let (|Int|_|) s = 
    match System.Int32.TryParse s with 
    | true, v -> Some v 
    | _ -> None 

let getWoeid args = 
    match args with 
    | [|Int v|] -> Some v 
    | _ -> None 
7

您還可以傳遞ByRef參數到TryParse代替允許它被tuplized。

let getWoeid args = 
    let mutable i = 0 
    match args with 
    | [|s|] when Int32.TryParse(s, &i) -> Some i 
    | _ -> None