common-lisp - 用于连接字符串列表的 lisp 函数

标签 common-lisp string-concatenation

我需要编写一个将列表连接成字符串的函数。例子:
(concatString (quote ("hello""world"))) ==> "hello world"

这是我到目前为止所拥有的:

(defun concatString (list)
  "A non-recursive function that concatenates a list of strings."
  (cond
   ((not (listp list))
     (princ "Error: argument to concatNR must be a list")(terpri) ())) ; check if parameter is a list

  (if (not (null list)) ;check if list is not null
      (let ((result (car list)))
        (dolist (item (cdr list))
          (if (stringp item)
              (setq result (concatenate result item)))          
        )
      )
  )
)

当我尝试运行它时,我收到一条“错误:“你好”是非法类型说明符的消息。我已经尝试了很多方法来修改这个函数,但我一直无法弄清楚。有没有人有任何想法?

最佳答案

concatenate需要一个序列类型说明符作为它的第二个参数。要连接两个字符串,您应该调用 concatenate作为:

(concatenate 'string "hello" "world")

代码中的另一个错误:您没有确保 car列表的 是一个字符串,然后将其分配给 result .通过修复您的代码,我想出了以下实现:
(defun concatString (list)
  "A non-recursive function that concatenates a list of strings."
  (if (listp list)
      (let ((result ""))
        (dolist (item list)
          (if (stringp item)
              (setq result (concatenate 'string result item))))
        result)))

;; tests
> (concatString (list "hello" " world"))
"hello world"
> (concatString (list "hello" 1 2 3 " world"))
"hello world"
> (concatString (list "hello" 1 2 "3" " world"))
"hello3 world"
> (concatString (list 1 2 3 "hello" " world"))
"hello world"

以下重新定义concatString效率更高,因为它不会创建许多中间字符串对象:
(defun concatString (list)
  "A non-recursive function that concatenates a list of strings."
  (if (listp list)
      (with-output-to-string (s)
         (dolist (item list)
           (if (stringp item)
             (format s "~a" item))))))

关于common-lisp - 用于连接字符串列表的 lisp 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5457346/

相关文章:

Java连接字符串、整数和 float 的最快方法

lisp - lisp 中的自定义 '+'(求和)函数

lisp - "Overloading"具有不同参数列表的 CLOS 多方法

javascript - 值 Javascript 输入

java - 将字符串连接到数组列表中

sql-server - nvarchar 连接/索引/nvarchar(max) 令人费解的行为

swift - 实例成员 API_KEY 不能用于类型 'DataType'

lisp - 如何使用 clisp 将字符串转换为列表?

lisp - Lisp首次搜索下的正向链接

common-lisp - OpenMCL Common Lisp 出现 "No MAKE-LOAD-FORM"错误