Common lisp 公共lisp:如何抑制换行符或;“软回报”;
此代码Common lisp 公共lisp:如何抑制换行符或;“软回报”;,common-lisp,Common Lisp,此代码 (defun arabic_to_roman (filename) (let ((arab_roman_dp '()) (arab nil) (roman nil)) (with-open-file (in filename :direction :input :if-does-not-exist nil)
(defun arabic_to_roman (filename)
(let ((arab_roman_dp '())
(arab nil)
(roman nil))
(with-open-file (in filename
:direction :input
:if-does-not-exist nil)
(when in
(loop for line = (read-line in nil)
while line do
(setq arab (subseq line 0 (search "=" line)))
(setq roman (subseq line (1+ (search "=" line)) (length line)))
(setf arab_roman_dp (acons arab roman arab_roman_dp))
;(format t "~S ~S~%" arab roman)
)))
(with-open-file (stream #p"ar_out.txt"
:direction :output
:if-exists :overwrite
:if-does-not-exist :create )
(write arab_roman_dp :stream stream :escape nil :readably nil))
'done!))
看来效果不错。它需要一个包含如下项的文件
1=I
2=II
...
并构建一个大的虚线对列表。但是,当我查看输出文件时,似乎插入了软返回或换行符
((4999 . MMMMCMXCIX) (4998 . MMMMCMXCVIII) (4997 . MMMMCMXCVII)
(4996 . MMMMCMXCVI) (4995 . MMMMCMXCV) (4994 . MMMMCMXCIV)
(4993 . MMMMCMXCIII) (4992 . MMMMCMXCII) (4991 . MMMMCMXCI) (4990 . MMMMCMXC)
...
我希望输出看起来更像一条连续的线:
((4999 . MMMMCMXCIX) (4998 . MMMMCMXCVIII) (4997 . MMMMCMXCVII) (4996 . MMMCMXCVI) (4995 . MMMMCMXCV) (4994 . MMMMCMXCIV) (4993 . MMMMCMXCIII) (4992 . MMMMCMXCII) (4991 . MMMMCMXCI) (4990 . MMMMCMXC) ...
我的代码是否真的以某种方式加入了换行符?我使用了
write
版本的princ
,据说它会抑制换行符。稍后,我想将此文件作为一个大列表读回程序中,因此我不希望出现换行问题。看起来正在调用漂亮的打印机(默认值取决于实现),以缩进和人类可读的行长度打印它。使用:pretty nil
禁用此功能
(write arab_roman_dp :stream stream :escape nil :readably nil :pretty nil)
看起来正在调用pretty打印机(默认值取决于实现),以使用缩进和人类可读的行长度打印它。使用
:pretty nil
禁用此功能
(write arab_roman_dp :stream stream :escape nil :readably nil :pretty nil)
更好的写作方法:
- 使用函数创建可以组合的代码块
- 副作用少,变量少
- 无需在
- 易于理解的控制流
(defun arabic_to_roman (filename)
(flet ((read-it ()
(with-open-file (in filename
:direction :input
:if-does-not-exist nil)
(loop for line = (read-line in nil)
for pos = (position #\= line)
while line collect (cons (subseq line 0 pos)
(subseq line (1+ pos))))))
(write-it (list)
(with-open-file (stream #p"ar_out.txt"
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(write list :stream stream :escape nil :readably nil :pretty nil))))
(write-it (read-it))
'done-read-write))
更好的写作方法:
- 使用函数创建可以组合的代码块
- 副作用少,变量少
- 无需在
- 易于理解的控制流
(defun arabic_to_roman (filename)
(flet ((read-it ()
(with-open-file (in filename
:direction :input
:if-does-not-exist nil)
(loop for line = (read-line in nil)
for pos = (position #\= line)
while line collect (cons (subseq line 0 pos)
(subseq line (1+ pos))))))
(write-it (list)
(with-open-file (stream #p"ar_out.txt"
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(write list :stream stream :escape nil :readably nil :pretty nil))))
(write-it (read-it))
'done-read-write))
如果使用Lisp读取器读回,换行符无论如何都不是问题。如果使用Lisp读取器读回,换行符无论如何都不是问题。