Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Pattern Matching with when clause

Tags:

f#

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
like image 517
Knows Not Much Avatar asked Nov 29 '22 14:11

Knows Not Much


2 Answers

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
like image 61
desco Avatar answered Dec 04 '22 15:12

desco


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
like image 32
Daniel Avatar answered Dec 04 '22 13:12

Daniel