lisp - 符号表达式流 I/O

标签 lisp common-lisp s-expression

在 Common Lisp 中,如何从流中读写符号表达式?例如,我可能想将一个匿名函数写入文件,然后读取并调用它:

;;; sexp-io.lisp
;;; Try writing a sexp to file and reading it back in

(with-open-file (file "~/Documents/Lisp/Concurrency/sexp.lisp"
                  :direction :output :if-exists :supersede)
  (print #'(lambda () (+ 1 1)) file))

(with-open-file (file "~/Documents/Lisp/Concurrency/sexp.lisp"
                  :direction :input)
  (read file))

但是,该代码会导致可疑的输出

 #<Anonymous Function #x3020018F950F>

当我尝试读回它时确实会导致错误:

> Error: Reader error on #<BASIC-FILE-CHARACTER-INPUT-STREAM ("/Users/frank/Documents/Lisp/Concurrency/sexp.lisp"/7 UTF-8) #x3020018F559D>, near position 3, within "
>        #<Anonymous ":
>        "#<" encountered.
> While executing: CCL::SIGNAL-READER-ERROR, in process Listener(4).

最佳答案

你正在做 TRT , 除了 #'这变成了list (lambda () (+ 1 1)) 变成 function目的。只需将尖引号(读作 function )替换为简单引号(读作 quote )即可,它应该可以工作。

您可能想要进行的另一项更改是替换 print with write带参数 :readably t:

(write my-object :stream out :readably t)

:readably 的好处是,如果它不能以保持打印-读取一致性的方式写入,它就会失败。

关于lisp - 符号表达式流 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379436/

相关文章:

lisp - 获取彩票号码

lisp - map 车到位 : destructively modify a list of lists

java - Java 中 Lisp 表达式的拆分

functional-programming - 列表作为通用数据类型表示的缺点是什么?

function - LISP - CONS 需要做什么工作?

algorithm - SICP - 练习 2.63 - 确定增长顺序

recursion - 如何使用递归合并按字母顺序排列的两个字符串

common-lisp - common-lisp中有关可选参数的错误

lisp:采用初始列表并将其与其他列表进行比较的函数

vim - Clojure 中的 Slurpage 和 Barfage