Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: compare characters

Tags:

clojure

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))
like image 647
demi Avatar asked Oct 22 '25 05:10

demi


2 Answers

(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)))
like image 99
A. Webb Avatar answered Oct 24 '25 10:10

A. Webb


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.

like image 27
Alex Avatar answered Oct 24 '25 08:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!