How to cast a character to int in Clojure?
I am trying to write a rot 13 in clojure, so I need to have something to cast my char to int. I found something called (in
What you are looking for is a character literal \a
. A character literal is denoted by a single character, or 16-bit unicode code point, prefixed by the \
reader macro.
(int \a) ;; => 97
(int \0) ;; => 48
(int \u0030) ;; => 48
With (int a)
, a
is a symbol. As such, the runtime tried and failed to resolve what that symbol was bound to.
With (int 'a)
, a
is also a symbol, but, because you declared it a symbol with the single quote ('
), the runtime took it literally and tried and faild to cast the clojure.lang.Symbol
to a java.lang.Character
.
With (rot13 ''a')
, 'a'
declares a'
as a symbol. But, the extra '
prefixing it makes the runtime treat the expression that declared the a'
literally. 'a'
expands to (quote a')
, so the "literal literal", ''a'
, expands to the list (quote a')
.
''a' ;; => (quote a')
(second ''a') ;; => a'
With (rot13 "a")
, a
is a string. Strings cannot be cast to characters, but they can be treated as collections of characters. So, (rot13 (first "a"))
would work as intended.