In C++ world, I can do like this (characters are comparable):
bool isDigit(char c) {
return '0' <= c && c <= '9';
}
In Clojure, I can compare for equality, but can compare with less:
(= \a \b) ; [compiles] false
(< \a \b) ; java.lang.Character cannot be cast to java.lang.Number
How can I implement this in Clojure? How can I check if a character in a range? I can do it in heavy-weight style like this:
(defn isDigit [c] (#{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9} c))
(defn digit? [c] (and (>= 0 (compare \0 c))
(>= 0 (compare c \9))))
(defn digit?? [c] (= (java.lang.Character/getType ^Character c)
(java.lang.Character/DECIMAL_DIGIT_NUMBER)))
(defn digit??? [c] (re-find #"\d" (str c)))
You can use an int coercion if you want to check whether a character falls in some range:
(let [zero (int \0)
nine (int \9)]
(defn is-digit? [c] (<= zero (int c) nine)))
Alternatively, you could call directly to the Character.isDigit method, if all you need to check for is digits. Clearly that won't work for ranges that aren't predefined character classes.
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