Put an element to the tail of a collection

后端 未结 4 856
北海茫月
北海茫月 2021-02-02 05:25

I find myself doing a lot of:

(concat coll [e]) where coll is a collection and e a single element.

Is there a function for doing this in Clojure? I

4条回答
  •  礼貌的吻别
    2021-02-02 06:18

    To distill the best of what amalloy and Laurent Petit have already said: use the conj function.

    One of the great abstractions that Clojure provides is the Sequence API, which includes the conj function. If at all possible, your code should be as collection-type agnostic as it can be, instead using the seq API to handle operations on collections and picking a particular collection type only when you need to be specific.

    If vectors are a good match, then yes, conj will be adding items onto the end. If use lists instead, then conj will be adding things to the front of your collection. But if you then use the standard seq API functions for pulling items from the "top" of a collection (the back of a vector, the front of a list), it doesn't matter which implementation you use, because it will always use the one with best performance and thus adding and removing items will be consistent.

提交回复
热议问题