符号表达流I / O.

时间:2015-03-31 22:07:48

标签: 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).

1 个答案:

答案 0 :(得分:5)

您正在执行TRT,但#'list (lambda () (+ 1 1))转换为function对象除外。只需用一个简单的引号(读作function)替换sharp-quote(读作quote),它就应该有效。

您可能想要做的另一项更改是使用参数:readably t替换print with write

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

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

相关问题