如何在源代码中跨多行编写单行字符串文字
How to write a single line string literal across multiple lines in the source code
我想得到这个单行字符串值:
"pineapple"
但是在源代码中,我想把字符串写成多行:
"pine
apple"
但是,上面的多行代码将 return 一个包含换行符的字符串。有没有办法阻止 returned 换行?
在Scheme和Emacs Lisp等其他Lisp中,可以通过在行尾添加反斜杠\
来抑制换行:
;; In Scheme and Emacs Lisp, this returns "pineapple":
"pine\
apple"
然而,在 Common Lisp 中,在行尾放置反斜杠没有任何效果:
;; Common Lisp:
(string-equal "pine\
apple"
"pine
apple")
;; Returns: T
如何在源代码中跨多行编写单行字符串文字?
格式使用~换行符directive。
(string-equal (format nil "multi-~
line ~
pine~
apple")
"multi-line pineapple")
我认为,一个好的方法是定义一个增强的字符串 reader,它允许文字字符串有更多的可能性。这不是很难做到,我希望有很多人潜伏在角落里。我碰巧非常了解的一个是 stringtables。这样做是为文字字符串提供一个以 CL 可读表为模型的系统(但显然更简单)。字符串中可以有特殊字符,类似于在 CL 可读表中调度宏字符(没有等同于普通宏字符的东西,因为这似乎没有用)。有一个默认的特殊字符 #\~
.
该系统相当通用,但它有几个实用程序,可以让您以最简单的方式使用它。这是其中的一个例子。
首先设置可读表,这样写成 #" ..."
的字符串将使用字符串表进行解析(*stringtable*
是字符串表,使用方式与 *readtable*
相同使用的可读表):
> (setf *readtable* (make-stringtable-readtable :delimiter #\"))
#<readtable 402006239B>
现在配置 *stringtable*
有一个换行符和一些会在可能的拙劣的换行跳过时发出警告的东西:
> (set-stringtable-newline-skipper :stringtable *stringtable*)
#<stringtable 421018687B>
现在我们可以测试了:
> (read)
"this is an oordinary
string"
"this is an oordinary
string"
> (read)
#"this string is read
with a stringtable"
"this string is read
with a stringtable"
> (read)
#"this string has an ~
ignored newline"
"this string has an ignored newline"
> (read)
#"this string has a botched ~
ignored newline"
Warning: ~ followed by space: did you mean newline?
"this string has a botched
ignored newline"
我想得到这个单行字符串值:
"pineapple"
但是在源代码中,我想把字符串写成多行:
"pine
apple"
但是,上面的多行代码将 return 一个包含换行符的字符串。有没有办法阻止 returned 换行?
在Scheme和Emacs Lisp等其他Lisp中,可以通过在行尾添加反斜杠\
来抑制换行:
;; In Scheme and Emacs Lisp, this returns "pineapple":
"pine\
apple"
然而,在 Common Lisp 中,在行尾放置反斜杠没有任何效果:
;; Common Lisp:
(string-equal "pine\
apple"
"pine
apple")
;; Returns: T
如何在源代码中跨多行编写单行字符串文字?
格式使用~换行符directive。
(string-equal (format nil "multi-~
line ~
pine~
apple")
"multi-line pineapple")
我认为,一个好的方法是定义一个增强的字符串 reader,它允许文字字符串有更多的可能性。这不是很难做到,我希望有很多人潜伏在角落里。我碰巧非常了解的一个是 stringtables。这样做是为文字字符串提供一个以 CL 可读表为模型的系统(但显然更简单)。字符串中可以有特殊字符,类似于在 CL 可读表中调度宏字符(没有等同于普通宏字符的东西,因为这似乎没有用)。有一个默认的特殊字符 #\~
.
该系统相当通用,但它有几个实用程序,可以让您以最简单的方式使用它。这是其中的一个例子。
首先设置可读表,这样写成 #" ..."
的字符串将使用字符串表进行解析(*stringtable*
是字符串表,使用方式与 *readtable*
相同使用的可读表):
> (setf *readtable* (make-stringtable-readtable :delimiter #\"))
#<readtable 402006239B>
现在配置 *stringtable*
有一个换行符和一些会在可能的拙劣的换行跳过时发出警告的东西:
> (set-stringtable-newline-skipper :stringtable *stringtable*)
#<stringtable 421018687B>
现在我们可以测试了:
> (read)
"this is an oordinary
string"
"this is an oordinary
string"
> (read)
#"this string is read
with a stringtable"
"this string is read
with a stringtable"
> (read)
#"this string has an ~
ignored newline"
"this string has an ignored newline"
> (read)
#"this string has a botched ~
ignored newline"
Warning: ~ followed by space: did you mean newline?
"this string has a botched
ignored newline"