在结果向量中用填充指针合并两个向量

Merging two vectors with fill-pointer in the resulting vector

我有两个带有填充指针的向量。我需要 merge 这些向量,结果是一个仍然有填充指针的新向量。

(defparameter *a* (make-array 3 :fill-pointer 3
                                :initial-contents '(1 3 5)))
(defparameter *b* (make-array 3 :fill-pointer 3
                                :initial-contents '(0 2 4)))
(type-of *a*)
;;=> (VECTOR T 6)

;; Pushing new elements works as intended.
(vector-push-extend 7 *a*)
(vector-push-extend 6 *b*)
;; Now we create a new vector by merging *a* and *b*.
(defparameter *c* (merge 'vector *a* *b* #'<))
;;=> #(0 1 2 3 4 5 6 7)
(type-of *c*)
;;=> (SIMPLE-VECTOR 8)

;; The type of this new vector does not allow pushing elements.
(vector-push-extend 8 *c*)

;; The value
;;   #(0 1 2 3 4 5 6 7)
;; is not of type
;;   (AND VECTOR (NOT SIMPLE-ARRAY))
;;    [Condition of type TYPE-ERROR]

我似乎找不到要指定给 merge 的类型,以便结果具有填充指针。我想明显的解决方法是:

当然,如果有一种方法可以使用标准中的 merge 来做到这一点,那么这两种解决方法都不能令人满意。

确实没有简单的方法可以得到merge return一个vector一个 fill-pointer.

但是,您可以置换您的结果向量:

(defparameter *c* (merge '(vector t) *a* *b* #'<))
(type-of *c*)
==> (SIMPLE-VECTOR 8)
(defparameter *d* (make-array (length *c*) :displaced-to *c* :fill-pointer t))
(type-of *d*)
==> (VECTOR T 8)
*d*
==> #(0 1 2 3 4 5 6 7)
(array-displacement *d*)
==> #(0 1 2 3 4 5 6 7); 0
(vector-push-extend 17 *d*)
==> 8
*d*
==> #(0 1 2 3 4 5 6 7 17)

到目前为止还不错吧?

不,没那么快:

(array-displacement *d*)
==> NIL; 0

当我们打电话时 vector-push-extend*d*,它从置换数组转换为普通数组 因为底层 simple-vector 无法延长。

如果您愿意,您实际上可以考虑使用列表而不是数组 使用 merge 因为它在列表上更有效(重用 结构)。