Clojure:如何将clojure代码转换为可评估的字符串?它大多是工作,但列表被翻译为原始的括号,失败 [英] Clojure: How do I turn clojure code into a string that is evaluatable? It mostly works but lists are translated to raw parens, which fails

查看:128
本文介绍了Clojure:如何将clojure代码转换为可评估的字符串?它大多是工作,但列表被翻译为原始的括号,失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的简单结构:

 (def example {:bbbbbb:xxx [1 2 3 ]:yyy'(3 5 7)})



如果我把它写入文件,

  {:bbbbbb:xxx [1 2 3]:yyy(3 5 7)} 

这是大多数正确的,但如果我加载文件对此,它失败,因为它试图把3作为一个函数括号不再被引用,因此尝试作为一个函数求值)。



这样做的正确方法是什么?谢谢!

解决方案

如果要读回以前写为文件的Clojure数据, code>读取或读取字符串,而不是 load-file

 (with-open [fd(java.io.PushbackReader。
(io / reader路径/到/文件)))]
(读取fd))

调用多次读取以读取连续的表单(只要您持有 Reader 打开) p>

这不涉及任何评估,除非在输入流中出现#= 读取器宏,在这种情况下,它在读取时被评估并且被替换为读取的输出(例如(读字符串#=(+ 1 2)) )返回 3 )。禁止评估#= 前缀表单bind * read-eval * false


I have a simple structure like this:

(def example {:bbb "bbb" :xxx [1 2 3] :yyy '(3 5 7)})

If I write this out to a file it contains

{:bbb "bbb" :xxx [1 2 3] :yyy (3 5 7)}

Which is mostly correct, but if I load-file on this, it fails because it tries to treat 3 as a function (the parens are no longer quoted, so tries to evaluate as a function).

What is the right way to do this? Thanks!

解决方案

If you want to read back a Clojure datum previously written to a file as a literal, you need to use read or read-string rather than load-file:

(with-open [fd (java.io.PushbackReader.
                (io/reader (io/file "/path/to/file")))]
  (read fd))

You can call read multiple times to read successive forms (as long as you hold the Reader open, of course).

This involves no evaluation except when the #= reader macro occurs in the input stream, in which case the form immediately following it is evaluated at read time and replaced with the result in read's output (e.g. (read-string "#=(+ 1 2)") returns 3). To prohibit evaluation of #= prefixed forms bind *read-eval* to false.

这篇关于Clojure:如何将clojure代码转换为可评估的字符串?它大多是工作,但列表被翻译为原始的括号,失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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