Simplest way to ensure var is vector

[亡魂溺海] 提交于 2019-12-23 05:15:16

问题


What is the "simplest"/shortest way to ensure a var is a vector? Self-written it could look like

(defn ensure-vector [x]
  (if (vector? x)
    x
    (vector x))

(ensure-vector {:foo "bar"})
;=> [{:foo "bar"}]

But I wonder if there is already a core function that does this? Many of them (seq, vec, vector, list) either fail on maps or always apply.

I also wonder what would be the best name for this function. box, singleton, unit, v, cast-vector, to-vector, ->vector, !vector, vector!, vec!?

I further wonder if other languages, like Haskell, have this function built-in.


回答1:


I think the function you want to use when the value is a collection is vec which turns any collection into a vector. The vector function receives the items of the resulting vector as its arguments, so you could use it when the value is neither a vector or a collection.

This is a possible approach:

(defn as-vector [x]
  (cond
    (vector? x) x
    (sequential? x) (vec x)
    :else (vector x)))

(map as-vector [[1] #{2 3} 1 {:a 1}])

I chose the name for the function based on the ones from the Coercions protocol in clojure.java.io (as-file and as-url).



来源:https://stackoverflow.com/questions/17710570/simplest-way-to-ensure-var-is-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!