Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching numeric strings

I have a function that pattern matches its argument, which is a string:

let processLexime lexime
    match lexime with
    | "abc" -> ...
    | "bar" -> ...
    | "cat" -> ...
    | _     -> ...

This works as expected. However, I'm now trying to extend this by expressing "match a string containing only the following characters". In my specific example, I want anything containing only digits to be matched.

My question is, how can I express this in F#? I'd prefer to do this without any libraries such as FParsec, since I'm mainly doing this for learning purposes.

like image 553
OMGtechy Avatar asked Jan 23 '16 22:01

OMGtechy


2 Answers

You can use active patterns: https://msdn.microsoft.com/en-us/library/dd233248.aspx

let (|Integer|_|) (str: string) =
   let mutable intvalue = 0
   if System.Int32.TryParse(str, &intvalue) then Some(intvalue)
   else None

let parseNumeric str =
   match str with
     | Integer i -> printfn "%d : Integer" i
     | _ -> printfn "%s : Not matched." str
like image 181
Petr Avatar answered Nov 15 '22 06:11

Petr


One way would be an active pattern

let (|Digits|_|) (s:string) = 
    s.ToCharArray() |> Array.forall (fun c -> System.Char.IsDigit(c)) |> function |true -> Some(s) |false -> None

then you can do

match "1" with
|Digits(t) -> printf "matched"
like image 31
John Palmer Avatar answered Nov 15 '22 08:11

John Palmer