1

在 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).
4

1 回答 1

5

你正在做TRT,除了#'它把变成一个对象。只需用简单的引号(读作)替换尖引号(读作),它应该可以工作。list (lambda () (+ 1 1))functionfunctionquote

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

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

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

于 2015-03-31T22:28:23.133 回答