4

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
Knows Not Much
  • 30,395
  • 60
  • 197
  • 373

2 Answers2

13

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
desco
  • 16,642
  • 1
  • 45
  • 56
8

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
Daniel
  • 47,404
  • 11
  • 101
  • 179