在 Common Lisp 中,如何使用依赖于较短列表的 map 遍历较长的列表来将某些函数应用于较长的列表?

How do I loop over a longer list with map that depends on a shorter list wrapping it to apply some function to the longer list in Common Lisp?

基本上,我想要在 Common Lisp 中等效于此代码,但最好以更方便的方式。

(defun circular (items) 
  (setf (cdr (last items)) items))
(map 'list #'(lambda (x y) (+ x y)) 
     (circular '(1 2 3)) '(2 3 4 5))
;; ==> (3 5 7 6)

我认为你的代码已经足够好了。 (唯一的问题是你should not modify a quoted list)。

您需要做的就是恢复您发布的列表:

(defun map-circular (result-type function governing-sequence &rest reused-lists)
  "Apply `function` to successive sets of arguments in which one argument is obtained from each sequence.
The result has the length of `governing-sequence`."
  (let ((last-cells (mapcar (lambda (list)
                              (let ((cell (last list)))
                                (setf (cdr cell) list)
                                cell))
                            reused-lists)))
    (unwind-protect
         (apply #'map result-type function governing-sequence reused-lists)
      (dolist (cell last-cells)
        (setf (cdr cell) nil)))))

测试:

(defparameter l1 (list 1 2))
(defparameter l2 (list 1 2 3))
(map-circular 'list #'+ '(1 2 3 4) l1 l2)
==> (3 6 7 7)
l1
==> (1 2)
l2
==> (1 2 3)

如果你使用 SERIES 包,你可以使用 SERIES 函数:

Creates an infinite series that endlessly repeats the given items in the order given.

如果项目是静态已知的,即这有效。不是来自运行时给出的值列表。

下面,代码扫描一个列表,同时迭代无限系列 1 2 3 .... 两个系列与 mapping 并行迭代,如 sn,映射生成一系列(cons s n)。结果收集为列表:

(collect 'list
  (mapping ((s (scan 'list '(a b c d e f g h)))
            (n (series 1 2 3)))
    (cons s n)))

结果是:

((A . 1) (B . 2) (C . 3) (D . 1) (E . 2) (F . 3) (G . 1) (H . 2))

系列进行stream-fusion,扩展代码为:

(let* ((#:out-823 (list 1 2 3)))
  (let (#:elements-816
        (#:listptr-817 '(a b c d e f g h))
        #:items-821
        (#:lst-822 (copy-list #:out-823))
        #:items-826
        (#:lastcons-813 (list nil))
        #:lst-814)
    (declare (type list #:listptr-817)
             (type list #:lst-822)
             (type cons #:lastcons-813)
             (type list #:lst-814))
    (setq #:lst-822 (nconc #:lst-822 #:lst-822))
    (setq #:lst-814 #:lastcons-813)
    (tagbody
     #:ll-827
      (if (endp #:listptr-817)
          (go series::end))
      (setq #:elements-816 (car #:listptr-817))
      (setq #:listptr-817 (cdr #:listptr-817))
      (setq #:items-821 (car #:lst-822))
      (setq #:lst-822 (cdr #:lst-822))
      (setq #:items-826 ((lambda (s n) (cons s n)) #:elements-816 #:items-821))
      (setq #:lastcons-813 (setf (cdr #:lastcons-813) (cons #:items-826 nil)))
      (go #:ll-827)
     series::end)
    (cdr #:lst-814)))

如果需要传递任意列表给函数,可以通过调用(nconc list list)制作自己的循环列表,写起来更简单。因为你可能不想改变输入列表,你可以这样写:

(defun circularize (list)
  (let ((list (copy-list list)))
    (nconc list list)))