Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string only contains alphabets in F#

Tags:

f#

I have a string which should only contain alphabets. To check that I have written the following code

let isCorrectString(str:string) = 
 let isInRange x = (x > 64 && x < 91 ) || (x > 96 && x < 123) || x = 32
 not (str.Any(fun ch -> not (isInRange (ch :?> int)) ))

I am obviously using LINQ's `Any' extension method here. Is there any better way to write the above code ?

like image 1000
fahadash Avatar asked Mar 19 '23 20:03

fahadash


1 Answers

If you want to just verify that it's correct, you could do:

let isCorrectString(str:string) = 
    let isInRange x = (x > 64 && x < 91 ) || (x > 96 && x < 123) || x = 32
    let bad = 
        str
        |> Seq.map (fun c -> isInRange(int c))
        |> Seq.exists (fun b -> b = false)
    not bad

Note that this may be a simpler alternative:

let isCorrectString(str:string) = 
    str
    |> Seq.forall (fun c -> System.Char.IsLetter(c) || c = ' ')

Or, if you prefer:

let isCorrectString(str:string) = 
    str
    |> Seq.tryFind (fun c -> not(System.Char.IsLetter(c) || c = ' '))
    |> Option.isNone
like image 55
Reed Copsey Avatar answered Mar 28 '23 20:03

Reed Copsey