什么是惯用的方法prePEND在Clojure的载体? [英] What is the idiomatic way to prepend to a vector in Clojure?

查看:121
本文介绍了什么是惯用的方法prePEND在Clojure的载体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

prepending到一个列表很简单:

Prepending to a list is easy:

user=> (conj '(:bar :baz) :foo)
(:foo :bar :baz)

附加到一个向量很简单:

Appending to a vector is easy:

user=> (conj [:bar :baz] :foo) 
[:bar :baz :foo]

我如何(地道)prePEND为向量,而取回一个载体?
这不起作用,因为它返回一个序列,而不是一个向量:

How do I (idiomatically) prepend to a vector, while getting back a vector? This does not work as it returns a seq, not a vector:

user=> (cons :foo [:bar :baz])     
(:foo :bar :baz)

这是丑陋的(IMVHO):

This is ugly (IMVHO):

user=> (apply vector (cons :foo [:bar :baz])) 
[:foo :bar :baz]

请注意:我基本上只是希望有一个数据结构,我可以追加和prePEND来。追加到大名单应该有一个大的性能损失,所以我想的载体。

Note: I basically just want a datastructure that I can append and prepend to. Appending to large lists should have a large performance penalty, so I thought of vectors..

推荐答案

向量不会被设计为prepending。你只有为O(n)prePEND:

Vectors are not designed for prepending. You have only O(n) prepend:

user=> (into [:foo] [:bar :baz])
[:foo :bar :baz]

您需要的是最有可能是手指树

What you want is most likely a finger tree.

这篇关于什么是惯用的方法prePEND在Clojure的载体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆