Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a character is within a range in Clojure?

I'm trying to write a function that checks if a character is within a certain hexadecimal range.

I'm trying the code shown below:

(def current \s)
(and (>= current (char 0x20)) (<= current (char 0xD7FF)))

I get the following error:

java.lang.ClassCastException: java.lang.Character cannot be cast to 
java.lang.Number (NO_SOURCE_FILE:0)

I assume because the >= operator expects a number, it tries to type cast it.In regular java, I could just do:

(current >= 0x20) && (current <= 0xD7FF)
like image 310
tommy chheng Avatar asked Feb 12 '10 08:02

tommy chheng


2 Answers

explicitly convert it to an int first

(<= 0x20 (int current) 0xD7FF)
like image 54
cobbal Avatar answered Oct 31 '22 07:10

cobbal


Chars aren't numbers in Clojure though it's easy to cast them into characters with the int function.

(number? \a)       => false
(number? 42)       => true
(number? (int \a)) => true

For casts to primitive types you can use the function with the name of the type you want (see (find-doc #"Coerce")).

(int (char 0x20))
(float ...)
(map double [1 2 3 4])
 ....
like image 44
Arthur Ulfeldt Avatar answered Oct 31 '22 09:10

Arthur Ulfeldt