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 ?
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
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