如何生成一个重复的string?

期望:

(make-repeated-string "foo" 3)
=> "foofoofoo"

搜了一下只找到common lisp的:https://stackoverflow.com/questions/20072959/lisp-format-a-character-a-number-of-times ,用的cl的format,参数和elisp的不一样。

大概是dotimes+concat?

(defun make-repeated-string (x n)
  (apply #'concat
         (loop repeat n
               collect x)))
2 个赞

https://github.com/magnars/s.el/blob/03410e6a7a2b11e47e1fea3b7d9899c7df26435e/s.el#L121-L128

2 个赞
(apply #'concat (make-list 3 "foo"))
;; => "foofoofoo"

(cl-loop repeat 3 concat "foo")
;; => "foofoofoo"

(let (ret)
  (dotimes (_ 3)
    (setq ret (concat ret "foo")))
  ret)
;; => "foofoofoo"

(let ((i 0)
      ret)
  (while (< i 3)
    (setq ret (concat ret "foo")
          i (+ i 1)))
  ret)
;; => "foofoofoo"

(with-temp-buffer
  (dotimes (_ 3) (insert "foo"))
  (buffer-string))
;; => "foofoofoo"
2 个赞

效率上哪个比较有优势?

(apply #'concat (make-list 3 “foo”))

2 个赞

都差不多,或者说都足够快。

比较简洁的写法应该是 (apply #'concat (make-list 3 "foo"))

s-repeat 采用 cons + while 循环,而没有采用 make-list (c 实现是 cons + for)。在 elisp 和 c 中循环,效率差多少?

make-list

cons