"hello world" 这是我到目前为止所拥有的: (def-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:31:05 25 4
gpt4 key购买 nike

我需要编写一个将列表连接成字符串的函数。例子:
(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com