Put an element to the tail of a collection

后端 未结 4 865
北海茫月
北海茫月 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:13

    This is a very small addendum to @amalloy's answer in order to address OP's request for a function that always adds to the tail of whatever kind of collection. This is an alternative to (concat coll [x]). Just create a vector version of the original collection:

    (defn conj*
      [s x]
      (conj (vec s) x))
    

    Caveats:

    If you started with a lazy sequence, you've now destroyed the laziness--i.e. the output is not lazy. This may be either a good thing or a bad thing, depending on your needs.

    There's some cost to creating the vector. If you need to call this function a lot, and you find (e.g. by benchmarking with Criterium) that this cost is significant for your purposes, then follow the other answers' advice to try to use vectors in the first place.

提交回复
热议问题