Erica Maine
Erica Maine

Reputation: 147

How to map from characters to numbers in clojure?

How to map from characters to numbers in clojure?

Like I have a function:

(defn letter [c]
(str (last c)))

If I input: user => (letter "4R"), then I want the output as R. How to map the string value "R" to R?

Upvotes: 0

Views: 936

Answers (2)

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17771

R is not a number. A literal R in Clojure is a symbol. You can make symbols from strings using symbol - i.e. (symbol "R") => R

As @noisesmith said, characters (written as \R, for example) are also not numbers in Clojure/Java. It's not completely clear what you're asking, so if this isn't helpful please expand your question a little more - for instance, explain what you're actually trying to achieve.

Upvotes: 2

noisesmith
noisesmith

Reputation: 20194

In the jvm, a character is not a number.

user> (last "4R")
\R
user> (type (last "4R"))
java.lang.Character

It is easy to make a number out of one though.

user> (int (last "4R"))
82

In clojurescript there is no character datatype, so the approach is different

cljs.user=> (.charCodeAt (last "4R") 0)
82

Upvotes: 5

Related Questions