I was asked how would I parse the string "1/4" in Clojure. I replied the following (there are probably nicer ways):
(-> "1/25"
(str/split #"/")
(->> (map #(Integer/parseInt %))
(apply /)))
But then I thought I'll just see what read-string does (I use it for parsing when its safe), and surprisingly:
(read-string "1/25")
Returns a clojure.lang.Ratio
.
I didn't expect it to be able to read the expression at all. Can anyone explain why this works?
Both clojure.core/read
and clojure.edn/read
are a "superset" of the EDN spec. They supports all valid EDN's and some other's extensions (for example, ratios)
clojure.core/read
can evaluare code. for example (read-string "#=(prn :hello-injection)")
, so prefer clojure.edn/read-string
to parse inputs
AFIK, the cljs.core/read-string
will not read ratios. also you can't use 1/2
in .cljs
files.