我正在寻找一种非常适合以下操作的顺序数据结构。列表的长度保持不变,它永远不会长或短于固定长度。
省略第一项,并在末尾添加 x。
(0 1 2 3 4 5 6 7 8 9)
(pop-and-push "10")
(1 2 3 4 5 6 7 8 9 10)
只有另外一个读取操作必须同样频繁地执行:
(last coll)
弹出和推送可以像这样实现:
(defn pop-and-push [coll x]
(concat (pop coll) ["x"]))
(不幸的是,这不适用于例如 Range 生成的序列,它只是在传递文字"(...(声明的序列时弹出。
但这是最佳的吗?
这里的主要问题(一旦我们将"x"
更改为x
(是concat
返回一个lazy-seq
,而懒惰的seqs是无效的参数pop
。
user=> (defn pop-and-push [coll x] (concat (pop coll) [x]))
#'user/pop-and-push
user=> (pop-and-push [1 2 3] 4)
(1 2 4)
user=> (pop-and-push *1 5)
ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.IPersistentStack clojure.lang.RT.pop (RT.java:730)
我天真的偏好是使用向量。此功能很容易通过subvec
实现。
user=> (defn pop-and-push [v x] (conj (subvec (vec v) 1) x))
#'user/pop-and-push
user=> (pop-and-push [1 2 3] 4)
[2 3 4]
user=> (pop-and-push *1 5)
[3 4 5]
如您所见,此版本实际上可以对自己的返回值进行操作
正如注释中所建议的,PersistentQueue 是针对这种情况创建的:
user=> (defn pop-and-push [v x] (conj (pop v) x))
#'user/pop-and-push
user=> (pop-and-push (into clojure.lang.PersistentQueue/EMPTY [1 2 3]) 4)
#object[clojure.lang.PersistentQueue 0x50313382 "clojure.lang.PersistentQueue@7c42"]
user=> (into [] *1)
[2 3 4]
user=> (pop-and-push *2 5)
#object[clojure.lang.PersistentQueue 0x4bd31064 "clojure.lang.PersistentQueue@8023"]
user=> (into [] *1)
[3 4 5]
PersistentQueue 数据结构虽然在某些方面不太方便使用,但实际上是针对这种用法进行了优化的。