符号表达式流 I/O
symbolic expression stream I/O
在 Common Lisp 中,如何读写符号表达式 from/to 流?例如,我可能想将一个匿名函数写入文件,然后读取并调用它:
;;; 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, except for #'
which turns the list
(lambda () (+ 1 1))
into a function
object. Just replace the sharp-quote (which is read as function
) with a simple quote (which is read as quote
),应该可以。
您可能想要进行的另一项更改是将 print
with write
替换为参数 :readably t
:
(write my-object :stream out :readably t)
:readably
的好处是,如果它不能以保持打印-读取一致性的方式写入,它就会失败。
在 Common Lisp 中,如何读写符号表达式 from/to 流?例如,我可能想将一个匿名函数写入文件,然后读取并调用它:
;;; 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, except for #'
which turns the list
(lambda () (+ 1 1))
into a function
object. Just replace the sharp-quote (which is read as function
) with a simple quote (which is read as quote
),应该可以。
您可能想要进行的另一项更改是将 print
with write
替换为参数 :readably t
:
(write my-object :stream out :readably t)
:readably
的好处是,如果它不能以保持打印-读取一致性的方式写入,它就会失败。