在Clojure中修改Clojure源代码文件 [英] Modify Clojure source code file in clojure

查看:82
本文介绍了在Clojure中修改Clojure源代码文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将Clojure .clj 源文件中包含的代码作为列表加载而不进行编译。

I was wondering if it's possible to load the code contained in a Clojure .clj source file as a list, without compiling it.

如果我可以将 .clj 文件作为列表加载,则可以修改该列表并将其漂亮地打印回同一文件中,然后

If I can load a .clj file as a list, I can modify that list and pretty print it back into the same file which can then be loaded again.

(也许这是一个坏主意。)有人知道这是否可能吗?

(Maybe this is a bad idea.) Does anyone know if this is possible?

推荐答案

一个简单的示例:

user=> (def a '(println (+ 1 1))) ; "'" escapes the form to prevent immediate evaluation
#'user/a
user=> (spit "test.code" a) ; write it to a file
nil

user=> (def from-file (read-string (slurp "test.code"))) ; read it from a file
#'user/from-file
user=> (def modified (clojure.walk/postwalk-replace {1 2} from-file)) ; modify the code
#'user/modified
user=> (spit "new.code" modified) ; write it back
nil
user=> (load-string (slurp "new.code")) ; check it worked!
4
nil

在哪里 lur口给您一个字符串, read-string 给您一个未求值的表格,而 load-string 给您评估表单的结果。

Where slurp gives you a string, read-string gives you an un-evaluated form, and load-string gives you the result of evaluating the form.

这篇关于在Clojure中修改Clojure源代码文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆