Hello I have written the following code.
My objective was to write a function called getWoeid which will check if the command line parameter is an array with 1 element, and that element is an integer.
My code works... but I am calling the TryParse method two times... I wonder if there is a way in which I can call this only once.
Also, can you confirm if this way of using pattern matching for validating command line parameters is correct?
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
You can define active pattern:
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
You can also pass a byref parameter to TryParse
instead of allowing it to be tuplized.
let getWoeid args =
let mutable i = 0
match args with
| [|s|] when Int32.TryParse(s, &i) -> Some i
| _ -> None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With