I'm trying to write a function that checks if a character is a number.
I have:
isNumber:: Int -> Bool
isNumber x = x >= 0 || x >= 0
also tried it with Guards, same problem.
isNumber2:: Int -> Bool
isNumber2 x
| x >= 0 = True
| x <= 0 = True
| otherwise = False
When I enter a number it works, it says true. If I enter a character, an error comes out because a character is not an int. So I'm wondering if you can write something else instead of Int so that you can enter numbers and characters without an error coming up.
I tried multiple different Typesignatures, but didnt work.
CodePudding user response:
If you want to know if a character is a digit, your function probably needs to accept a Char
as its argument.
Now, Data.Char.ord
returns the numeric code for a character.
Prelude Data.Char> ord '7'
55
Prelude Data.Char> ord '0'
48
Prelude Data.Char> ord '1'
49
You may observe that they are in order:
Prelude Data.Char> ord '7' - ord '0'
7
This math can readily turn a Char
into its corresponding Int
, and this should allow you to use the logic you've already shown to accomplish your goal.
CodePudding user response:
There's also a built-in function in the Data.Char
module called isDigit :: Char -> Bool
which checks if a character is a digit.