Warm tip: This article is reproduced from serverfault.com, please click

clojure read-string fraction / ratio surprisingly working

发布于 2020-12-01 14:54:01

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?

Questioner
Reut Sharabani
Viewed
0
souenzzo 2020-12-02 02:03:34

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.