Clojure: sequence back to vector

前端 未结 4 1048
Happy的楠姐
Happy的楠姐 2021-01-01 18:33

How can I cast a sequence back to vector after a sequence producing operation (like sort)? Does using (vec..) on a sequence that was a vector is costly?

One (bad?)

4条回答
  •  灰色年华
    2021-01-01 19:40

    Meikel Brandmeyer just posted a solution to this on the Clojure group.

    (defn sorted-vec
      [coll]
      (let [arr (into-array coll)]
        (java.util.Arrays/sort arr)
        (vec arr)))
    

    Clojure's sort returns a seq across a sorted array; this approach does much the same thing, but returns a vector, not a seq.

    If you wish, you can even skip the conversion back into a Clojure persistent data structure:

    (defn sorted-arr
      "Returns a *mutable* array!"
      [coll]
      (doto (into-array coll)]
        (java.util.Arrays/sort))
    

    but the resulting Java array (which you can treat as a Clojure collection in most cases) will be mutable. That's fine if you're not handing it off to other code, but be careful.

提交回复
热议问题