I have been teaching myself OCaml
and having been trying to look through the Pervasives
module and others modules to find a module that contains a function that is like C/C++ functions isdigit
and isalpha
in an attempt to clean up my code a little.
As one of my conditional statements for checking for a letter looks like:
if token > 64 && token < 91 || token > 96 && token < 123 then (* Do something * )
Does OCaml
have a module that would be the equivalent of isdigit
and isalpha
?
The isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it's a digit else it returns 0. For example, it returns a non-zero value for '0' to '9' and zero for others. The isdigit() is declared inside ctype. h header file.
A module can provide a certain number of things (functions, types, submodules, ...) to the rest of the program that is using it. If nothing special is done, everything which is defined in a module will be accessible from the outside.
isalpha() and isdigit() in C/C++It returns an integer value, if the argument is an alphabet otherwise, it returns zero. Here is the syntax of isalpha() in C language, int isalpha(int value); Here, value − This is a single argument of integer type.
C isalpha() In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0. The isalpha() function is defined in <ctype.
One solution is to use pattern-matching over character ranges:
let is_alpha = function 'a' .. 'z' | 'A' .. 'Z' -> true | _ -> false
let is_digit = function '0' .. '9' -> true | _ -> false
Using @octachron solution of using pattern-matching I was able to create my own isalpha
and isdigit
functions to clean up my code.
Solution code:
(* A function that will validate if the input is a ALPHA *)
let is_alpha alpha =
match alpha with
'a' .. 'z' -> true
| 'A' .. 'Z' -> true
| _ -> false;;
(* A function that will validate if the input is a DIGIT *)
let is_digit digit =
match digit with
'0' .. '9' -> true
| _ -> false;;
let get_token token =
if (is_alpha (char_of_int token)) = true
then (* Checking if a APLHA was found *)
begin
Printf.printf("Valid Token Alpha found: %c\n") (char_of_int token);
end
else (is_digit (char_of_int token)) = true
then (* Checking if a Digit was found*)
begin
Printf.printf("Valid Token Digit found: %c\n") (char_of_int token);
end
else
begin
Printf.printf("Invalid Token found: %c\n") (char_of_int token);
end
;;
Thank you for the help in finding a solution to me question @octachron.
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