fpt*_*fpt 1 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))
Run Code Online (Sandbox Code Playgroud)
但是,该代码导致可疑输出
#<Anonymous Function #x3020018F950F>
Run Code Online (Sandbox Code Playgroud)
当我尝试将其读回时会导致错误:
> 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).
Run Code Online (Sandbox Code Playgroud)
你正在做TRT,除了#'把它变成一个对象.只需用一个简单的引号(读作为)替换sharp-quote(读作),它应该可以工作.list (lambda () (+ 1 1))functionfunctionquote
你可能想使另一个变化是更换print与write带有参数:readably t:
(write my-object :stream out :readably t)
Run Code Online (Sandbox Code Playgroud)
好处:readably是,如果它不能以保持打印读取一致性的方式写入,它就会失败.