Difference between read-string and load-string in Clojure

放肆的年华 提交于 2020-01-02 01:15:10

问题


I have some code which works after replacing read-string with load-string. It is good that the code works, but I would like to know why. What is the difference between the two clojure functions?


回答1:


Use load-string to sequentially read and evaluate the set of forms contained in the string

Use read-string to read one object from the string s

(both quoted from Clojure API)

Load-string will evaluate your string as a Clojure expression, and read-string takes the string and returns it as the found data structure, in which case might be an expression.

Protip: (load-string "(+ 1 2)") and (eval (read-string "(+ 1 2)")) will give you the same result, which is 3




回答2:


Two notable differences:

read-string reads but does not evaluate, while load-string reads and evaluates.

(read-string "(inc 1)") => (inc 1)
(load-string "(inc 1)") => 2

read-string only reads the first form in the string, while load-string loads all the forms in the string.

(read-string "1 2") => 1
(load-string "1 2") => 2


来源:https://stackoverflow.com/questions/4554694/difference-between-read-string-and-load-string-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!