在 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/