Common Lisp Concatenate和换行符

时间:2011-02-11 14:00:15

标签: sorting formatting lisp common-lisp

我目前正在编写一个LISP程序,它以下列列表的形式分析CR结果: (“I”0 10 0 20)<< (字X0 X1 Y0 Y1)

它必须使用单词的位置来构建整个文本。 我的代码有一个集群分析器,可以找到集群布局,例如左对齐或右对齐甚至两者的段落。集群数据结构如下所示: (“群集名称”xline y0 y1'(群集词))

当我迭代字符串列表并将它们连接到结果字符串以从这些字符串创建格式化文本时,如何添加新行? 示例:

"Hi,\n
\n
here is my entry\n
\n
Good bye"

我的代码如下:

(defun print-formatted-text(txt)
  (let
      ((size   (array-total-size txt))
       (sorted (sort (sort txt #'compare-mix) #'compare-generic2))
       (result ""))
    (loop for i from 0 to (1- size) do
          (let ((el (aref sorted i)))
            (if (word? el)
                (setf result (concatenate 'string result (first el) " "))
              (if (null (nth 7 el))
                  nil
                (progn
                  (setf result (concatenate 'string result " "))
                  (dolist (curr (nth 7 el))
                    (setf result (concatenate 'string result (first curr) " "))))))))
    result))

如果当前数据不是单词,那么它是一个段落。这意味着,我需要先添加一个新行,然后再将段落的内容输出。

这里是否正确使用了连接?

感谢您的建议。

4 个答案:

答案 0 :(得分:6)

我无法完全遵循您的计划,但使用字符串流并使用formatwrite-stringwrite-lineterpri和相关信息会更容易功能,例如

(let ((lines '("Hi," "Here is my entry" "Good bye")))
  (with-output-to-string (stream)
    (dolist (line lines)
      (write-line line stream)
      (terpri stream))))
=>
"Hi,

Here is my entry

Good bye

"

答案 1 :(得分:2)

关于编码风格的一些事情

(defun print-formatted-text(txt)
  (let
      ((size   (array-total-size txt))
       (sorted (sort (sort txt #'compare-mix) #'compare-generic2))
       (result ""))
    (loop for i from 0 to (1- size) do
          (let ((el (aref sorted i)))

(LOOP FOR e1 ACROSS已排序

            (if (word? el)
                (setf result (concatenate 'string result (first el) " "))

重复串联字符串真的很浪费。正如Xach所说,STREAMS是更好的抽象。

              (if (null (nth 7 el))
                  nil
                (progn

使用:(when (nth 7 e1)

                  (setf result (concatenate 'string result " "))
                  (dolist (curr (nth 7 el))
                    (setf result (concatenate 'string result (first curr) " "))))))))
    result))

答案 2 :(得分:1)

如果您在字符或换行符上使用连接,则需要将其括在括号中,使其成为一个列表,如'(#\Newline)

其中#\ Newline是换行符。

所有字符,例如从字符串中提取的字符,如(elt "abc" 1),都需要制作一个列表,例如(list (elt "abc" 1)

例如代码:

(concatenate 'string 
   "Hi ther" '(#\e) "." '(#\Newline) "How " (list #\a #\r #\e) " you!" )

=> "Hi there.
How are you!"

答案 3 :(得分:1)

您可以尝试

(s/exercise ::x 10 {::x #(s/gen string?)})
=>
(["" [:x-b ""]]
 ["" [:x-b ""]]
 ["" [:x-b ""]]
 ["" [:x-b ""]]
 ["13R0" [:x-b "13R0"]]
 ["7cT30" [:x-b "7cT30"]]
 ["uia0b" [:x-b "uia0b"]]
 ["" [:x-b ""]]
 ["bP" [:x-b "bP"]]
 ["4k2t6bW" [:x-b "4k2t6bW"]])

例如

(format nil "~%")